python修改pdf文件大小_python在將(pdf)轉換為jpeg時設置最大文件大小

For subsequent processing purposes, in python I am converting a multi-page PDF (f) into JPEGs (temp?.jpg):

為了后續的處理目的,在python中,我正在將一個多頁的PDF (f)轉換為jpeg (temp?.jpg):

import os

from wand.image import Image as wimage

with wimage(filename=f,resolution=300) as img:

for i in range(len(img.sequence)):

ftemp=os.path.abspath('temp%i.jpg'%i)

img_to_save=wimage(img.sequence[i])

img_to_save.compression_quality = 100

img_to_save.format='jpeg'

img_to_save.save(filename=ftemp)

I am using wand because of its ability to sequence the PDF pages, but am open to PIL etc.

我之所以使用wand,是因為它可以對PDF頁面進行排序,但對PIL等軟件開放。

I need the resolution and compression_quality to be as high as possible, but I want each JPEG to be no larger than (say) 300 kb in size.

我需要盡可能高的分辨率和compression_quality,但是我希望每個JPEG的大小不大於(比方說)300kb。

How can I set a limit to the size of the JPEG file?

如何限制JPEG文件的大小?

在命令行上,我只需這樣做(參見https://stackoverflow.com/a/11920384/1021819):

convert original.jpeg -define jpeg:extent=300kb -scale 50% output.jpg

Thanks!

謝謝!

1 个解决方案

#1

1

The wand library has wand.image.OptionDict for managing -define attributes, but unfortunately all options are locked by wand.image.Option frozenset. IMHO, this renders the whole feature as unusable.

魔棒庫有wand.image。用於管理-define屬性的選項,但不幸的是所有選項都被wand.image鎖定。選擇frozenset。IMHO,這使整個特性變得不可用。

Luckily, you can create a quick sub-class to handle this via the wand.api.

幸運的是,您可以通過wand.api創建一個快速子類來處理這個問題。

import os

from wand.image import Image

from wand.api import library

from wand.compat import binary

class wimage(Image):

def myDefine(self, key, value):

""" Skip over wand.image.Image.option """

return library.MagickSetOption(self.wand, binary(key), binary(value))

with wimage(filename=f, resolution=300) as img:

for i in range(len(img.sequence)):

ftemp=os.path.abspath('temp%i.jpg'%i)

with wimage(img.sequence[i]) as img_to_save:

img_to_save.myDefine('jpeg:extent', '300kb')

img_to_save.compression_quality = 100

img_to_save.format='jpeg'

img_to_save.save(filename=ftemp)

In the near future. The wand.image.Option would be deprecated, and you could simply call img_to_save.options['jpeg:extent'] = '300kb'.

在不久的將來。wand.image。選項將被廢棄,您可以簡單地調用img_to_save。選擇[' jpeg:程度上']= 300 kb。

你可能感兴趣的:(python修改pdf文件大小)