How to optimize image size using wand in python

陌路散爱 提交于 2019-12-03 13:23:32

Updated Answer

Setting the optimization with will require some additional MagickWand library extension/configuration. This is due to the quality attribute needing to be set on the wand data-structure, and not the image's instance. Confused? I am. Luckily Python's Wand library makes this easy. Try the following.

# Require wand's API library and basic ctypes
from wand.api import library
from ctypes import c_void_p, c_size_t

# Tell Python's wand library about the MagickWand Compression Quality (not Image's Compression Quality)
library.MagickSetCompressionQuality.argtypes = [c_void_p, c_size_t]

# Do work as before
from wand.image import Image

with Image(filename=filename) as img:
    img.resize(width=scaled_width, height=scaled_hight)
    # Set the optimization level through the linked resources of 
    # the image instance. (i.e. `wand.image.Image.wand`)
    library.MagickSetCompressionQuality(img.wand, 75)
    img.save(filename=output_destination)

Original Answer

There are many types of "optimization" for format, but I'm under the impression your seeking a way to reduce image size.

I believe wand.Image.compression_quality is what your looking for.

from wand.image import Image

with Image(filename=filename) as img:
    img.resize(width=scaled_width, height=scaled_hight)
    img.compression_quality = 75
    img.save(filename=output_destination)

The above will not reduce quality to 75% as you would expect with the JPEG format, but instruct which PNG-compression library/algo/filter to use. See PNG compression & Better PNG Compression examples.

+-----+
| 7 5 |
+-----+
| 0 . | Huffman compression (no-zlib)
| 1 . | zlib compression level 1
| 2 . | zlib compression level 2
| 3 . | zlib compression level 3
| 4 . | zlib compression level 4
| 5 . | zlib compression level 5
| 6 . | zlib compression level 6
| 7 . | zlib compression level 7
| 8 . | zlib compression level 8
| 9 . | zlib compression level 9
| . 0 | No data encoding/filtering before compression
| . 1 | "Sub" data encoding/filtering before compression
| . 2 | "Up" data encoding/filtering before compression
| . 3 | "Average" data encoding/filtering before compression
| . 4 | "Paeth" data encoding/filtering before compression
| . 5 | "Adaptive" data encoding/filtering before compression
+-----+

So setting the quality to 75 will compress using zlib level 7 after performing an adaptive filter. Note this is just the level and filter, not the optimization strategy. The optimization strategy can be set with the CLI option -define png:compression-strategy=zs however has yet to implement image artifact methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!