如何使用wand-py和imagemagick运行此命令

时间:2017-03-13 20:20:31

标签: python imagemagick-convert wand

我尝试使用wand-py和imagemagick重新创建以下命令:

convert -density 500 hello_world.pdf -quality 100 -monochrome -enhance – morphology close diamond hello_world.jpg

1 个答案:

答案 0 :(得分:2)

您需要绑定MagickCore和MagickWand库中的方法。请记住,内核性能在不同系统之间可能存在很大差异,因此如果您点击“取消操作”,请不要感到惊讶。处理大密度图像时出现错误信息。

import ctypes
from wand.api import libmagick, library
from wand.image import Image

"""
Kernel info methods on MagickCore library.
"""
libmagick.AcquireKernelInfo.argtypes = (ctypes.c_char_p,)
libmagick.AcquireKernelInfo.restype = ctypes.c_void_p
libmagick.DestroyKernelInfo.argtypes = (ctypes.c_void_p,)
libmagick.DestroyKernelInfo.restype = ctypes.c_void_p

"""
Morphology method on MagickWand library.
"""
library.MagickMorphologyImage.argtypes = (ctypes.c_void_p,  # wand
                                          ctypes.c_int,     # method
                                          ctypes.c_long,    # iterations
                                          ctypes.c_void_p)  # kernel
"""
Enhance method on MagickWand library.
"""
library.MagickEnhanceImage.argtypes = (ctypes.c_void_p,)    # wand

# convert -density 500 hello_world.pdf
with Image(filename='pdf-sample.pdf', resolution=500) as img:
    # -quality 100
    img.compression_quality = 100
    # -monochrome
    img.quantize(2,       # Target colors
                 'gray',  # Colorspace
                 1,       # Treedepth
                 False,   # No Dither
                 False)   # Quantization error
    # -enhance
    library.MagickEnhanceImage(img.wand)
    # -morphology close diamond
    p = ctypes.create_string_buffer(b'Diamond')
    kernel = libmagick.AcquireKernelInfo(p)
    CloseMorphology = 9  # See `morphology.h'
    library.MagickMorphologyImage(img.wand, CloseMorphology, 1, kernel)
    kernel = libmagick.DestroyKernelInfo(kernel) # Free memory
    # hello_world.jpg
    img.save(filename='hello_world.jpg')