天天看點

python 對png圖檔壓縮

從github上查找了很多python對圖檔壓縮的項目,發現大多用的都是基于pngquant的開發。

很多是基于指令行的方式開發。

然而pngquant工程中有個submodule,引用的是libimagequant工程。此工程目是給pngquant提供壓縮功能的。于是,我們可以針對這個工程做開發,以直接調用庫的方式壓縮圖檔。

libimagequant是一個c項目,是以我們需要找一個python binding,利用python-binding開發。

github中有兩個python binding。經過對比,選擇了本文要寫的這個,位址:GitHub - wladich/pyimagequant: python bindings for libimagequant (pngquant core)。

因為這個項目的開發者有明确和清晰的文檔說明,并且還提供了配合多個python庫(如PIL)使用的demo,很用心的項目。

接下來就是核心内容,不多,主要是引用和步驟的說明而已。想了解詳情的可以去上面的位址看看。

1.安裝

采用pip的方式:pip3 install libimagequant

2. 打開pycharm建立項目

3. 引用官方的demo即可使用,這裡貼出一個我的使用的小demo

工具類(這個直接從官方demo粘貼的)

import libimagequant as liq
import PIL.Image


def to_liq(image: PIL.Image.Image, attr: liq.Attr) -> liq.Image:
    """
        Convert PIL.Image.Image to liq.Image.
            """

    if image.mode != 'RGBA':
        image = image.convert('RGBA')

    return attr.create_rgba(image.tobytes(), image.width, image.height, image.info.get('gamma', 0))


def from_liq(result: liq.Result, image: liq.Image) -> PIL.Image.Image:
    """
        Convert liq.Image to PIL.Image.Image.
            """

    out_img = PIL.Image.frombytes('P',
                                  (image.width, image.height),
                                  result.remap_image(image))

    palette_data = []
    for color in result.get_palette():
        palette_data.extend(color[:3])
    out_img.putpalette(palette_data)

    return out_img
           

測試main

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import libimagequant as liq
import compression.test2 as tool
import PIL.Image as image


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    image = image.open("/usr/local/project/pylibimagequant/111.png")
    attr = liq.Attr()
    liq_image = tool.to_liq(image, attr)
    result = liq_image.quantize(attr)
    pil_image = tool.from_liq(result,liq_image)
    pil_image.save("/usr/local/project/pylibimagequant/111_compression.png")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
           

-------------------------------------      一些壓縮工具或者項目    -----------------------------------------------

1.pngquant,一個基于liimagequant的command line tool:

pngquant — lossy PNG compressor

2. 基于1的文章,又發現了其它的。如:

optipng

3. zopflipng.

4. 還有一篇測試文章,可以從裡面看到其它的壓縮工具:

https://css-ig.net/benchmark/png-lossless