如何在python中使用wand优化图像大小

时间:2016-01-05 17:12:49

标签: python optimization png wand

我想使用魔杖调整大小并优化png和jpg图像大小。

使用PIL,如果指定优化选项,我可以保存相同图像,大小约为3倍。

with open(filename, 'rb') as f:
    pimage = PImage.open(f)
    resized_pimage = pimage.resize((scaled_width, scaled_height), PImage.ANTIALIAS)            bytes_buffer = io.BytesIO()
    resized_pimage.save(bytes_buffer, format="PNG", optimize=True)

但是,我不确定Wand的等效选项是什么:

with default_storage.open(filename, 'rb') as f:
    img = WImage(file=f)
    img.resize(width=scaled_width, height=scaled_height, filter='gaussian')
    with WImage(width=scaled_width, height=scaled_height) as png:
        png.composite(img, top=0, left=0)
        png.format = 'png'
        bytes_buffer = io.BytesIO()
        png.save(file=bytes_buffer)

我读了几篇关于ImageMagic图像优化的文章(例如http://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/)但是我不知道如何在Wand中做这些(我在Wand或PIL中都是一个完整的新手)。

非常感谢任何帮助/指针。

1 个答案:

答案 0 :(得分:3)

更新答案

使用设置优化需要一些额外的MagickWand库扩展/配置。这是因为需要在quality数据结构上设置wand属性,而不是图像的实例。困惑?我是。幸运的是,Python的Wand库使这很容易。请尝试以下方法。

# 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)

原始答案

格式有许多类型的“优化”,但我的印象是你想要一种缩小图像尺寸的方法。

我相信wand.Image.compression_quality就是您的目标。

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)

上述内容不会像您期望的JPEG格式那样将质量降低到75%,但会指示使用哪个PNG压缩库/算法/过滤器。请参阅PNG compression & Better PNG Compression示例。

+-----+
| 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
+-----+

因此,在执行75过滤器后,将质量设置为7将使用zlib级别adaptive进行压缩。请注意,这只是级别和过滤器,而不是优化策略。可以使用CLI选项-define png:compression-strategy=zs设置优化策略,但尚未实现图像工件方法。