基于 PIL 和 OpenCV 库的PNG图像压缩的简单实现.

pngquant 工具可以对 PNG 进行压缩:

Ubuntu - pngquant PNG 图片压缩工具 - AIUAI

[1] - PIL

import os 
from PIL import Image 

png_file = '/path/to/demo.png'
print('[INFO]png file size: ', os.path.getsize(png_file))

png_pil = Image.open(png_file)
assert png_pil.mode == 'RGBA'
png_pil.save('/path/to/demo_out.png',"PNG",quality=75, optimize=True)

# 如果对质量要求再低些,
# 渐变的地方会出现失真
out_pil = png_pil.convert(mode="P", palette=Image.ADAPTIVE)
out_pil.save('/path/to/demo_out_p.png',"PNG",quality=75, optimize=True)

注:

[1] - 模式“P”为8位彩色图像,其每个像素用8个bit表示,其对应的彩色值是按照调色板查询出来的.

[2] - 模式“RGBA”为32位彩色图像,其每个像素用32个bit表示,其中24bit表示红色、绿色和蓝色三个通道,另外8bit 表示alpha通道,即透明通道.

[2] - OpenCV

import cv2 

png_file = '/path/to/demo.png'
print('[INFO]png file size: ', os.path.getsize(png_file))

img_cv2 = cv2.imread(png_file, cv2.IMREAD_UNCHANGED)
cv2.imwrite('/path/to/demo_out_cv2.png', img_cv2, [cv2.IMWRITE_PNG_COMPRESSION, 9])

注:

OpenCV 读取图像的 flag参数:

cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道
cv2.IMREAD_GRAYSCALE:读入灰度图片
cv2.IMREAD_UNCHANGED:读入完整图片,包括alpha通道

Last modification:November 2nd, 2020 at 05:53 pm