PNG压缩方案1, 转成WEBP,优选:
from PIL import Image
def convert_png_to_webp(png_path, webp_path):
# Open the PNG image
with Image.open(png_path) as img:
# Save the image in WEBP format
# img.save(webp_path, format='WEBP')
img.save(webp_path, format='WEBP', quality=80)
# Example usage
png_path = 'touming.png'
webp_path = 'touming.webp'
convert_png_to_webp(png_path, webp_path)
PNG压缩方案2, 使用zlip压缩:
import cv2
import numpy as np
import zlib
import io
def compress_image_zlib(image):
# 编码图像为 JPEG 格式的字节流
_, encoded_img = cv2.imencode('.jpg', image)
# 压缩字节流
compressed_img = zlib.compress(encoded_img.tobytes())
return compressed_img
def decompress_image_zlib(compressed_img):
# 解压缩字节流
decompressed_img = zlib.decompress(compressed_img)
# 将解压缩后的字节流转换为 NumPy 数组
nparr = np.frombuffer(decompressed_img, np.uint8)
# 解码为图像
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
# 读取图像
image = cv2.imread('example.jpg')
# 压缩图像
compressed_image = compress_image_zlib(image)
# 可以把compressed_image存到云端,前端获取解压缩图片
# 传输和接收 compressed_image ...
# 解压缩图像
decompressed_image = decompress_image_zlib(compressed_image)
# 显示解压缩后的图像
cv2.imshow('Decompressed Image', decompressed_image)
cv2.waitKey(0)
cv2.destroyAllWindows()