[英]How to optimize image size using wand in python
我想使用魔杖調整大小並優化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中做到這些(我是魔杖或PIL的完全新手。
任何幫助/指針將不勝感激。
使用wand設置優化需要一些額外的MagickWand庫擴展/配置。 這是因為需要在wand
數據結構上設置quality
屬性,而不是圖像的實例。 困惑? 我是。 幸運的是,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)
png格式有許多類型的“優化”,但我的印象是你想要一種減少圖像尺寸的方法。
我相信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壓縮和更好的PNG壓縮示例。
+-----+
| 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
+-----+
因此,在執行adaptive
濾波器后,將質量設置為75
將使用zlib 7
級進行壓縮。 請注意,這只是級別和過濾器,而不是優化策略。 可以使用CLI選項-define png:compression-strategy=zs
設置優化策略,但是wand尚未實現圖像工件方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.