本文介绍了python在使用例如转换(pdf)到jpeg时设置最大文件大小棍棒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了后续处理目的,我在python中将多页PDF( f )转换为JPEG格式( temp?.jpg ):

For subsequent processing purposes, in python I am converting a multi-page PDF (f) into JPEGs (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)

我正在使用魔杖,因为它能够对PDF页面进行排序,但我对PIL开放了等等。

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

我需要分辨率 compression_quality 来尽可能高,但我希望每个JPEG不大于(比方说)300 kb。

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.

如何设置限制大小为JPEG文件?

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

在命令行上我会做(见):

On the command line I would just do (see https://stackoverflow.com/a/11920384/1021819):

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

谢谢!

推荐答案

库有 wand.image.OptionDict 用于管理 -define 属性,但遗憾的是所有选项都被 wand.image.Option frozenset锁定。 恕我直言,这会使整个功能无法使用。

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.

幸运的是,你可以通过<$ c创建一个快速的子类来处理这个问题。 $ c> wand.api 。

Luckily, you can create a quick sub-class to handle this via the 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)

在不久的将来。 wand.image。选项将被弃用,您只需调用 img_to_save.options ['jpeg:extent'] ='300kb'

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

这篇关于python在使用例如转换(pdf)到jpeg时设置最大文件大小棍棒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 13:55