本文主要是介绍图片压缩算法优化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
正常的rgb三通道的图片用以下压缩算法没啥问题
def zip_img0(image_bytes):'''压缩图片 :param image_bytes::return:'''try:image_np = np.frombuffer(image_bytes, np.uint8)image = cv2.imdecode(image_np, cv2.IMREAD_COLOR)h, w, c = np.shape(image)max_size = 600ratio = min(1, min(max_size / h, max_size / w))# print(ratio)compressed_image = cv2.resize(image, [int(w * ratio), int(h * ratio)])# 将图像编码为WebP格式的字节流success, encoded_image = cv2.imencode('.webp', compressed_image, [int(cv2.IMWRITE_WEBP_QUALITY), 90])# 检查编码是否成功if success:# print(encoded_image)compressed_bytes = encoded_image.tobytes()return compressed_bytesexcept Exception as e:return None
但是对于RGBA类图像做压缩 背景就会变黑
如原图:
压缩之后:
一开始针对RGBA类型的,写了个判断处理
def zip_img1(image_bytes):'''压缩图片 有些是青紫色:param image_bytes: 原始图片的字节流:return: 压缩后的图片字节流'''try:# 将字节流转换为 NumPy 数组image_np = np.frombuffer(image_bytes, np.uint8)# 解码为图像,使用 IMREAD_UNCHANGED 以保留所有通道image = cv2.imdecode(image_np, cv2.IMREAD_UNCHANGED)if image is None:raise ValueError("Unable to decode the image")# 检查图像的通道数if image.shape[2] == 4: # RGBAprint('RGBA')# 将 RGBA 转换为 BGRAimage = cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA)elif image.shape[2] == 3: # RGB# 将 RGB 转换为 BGRimage = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)h, w, c = image.shapemax_size = 600ratio = min(1, min(max_size / h, max_size / w))# 缩放图像compressed_image = cv2.resize(image, (int(w * ratio), int(h * ratio)))# 将图像编码为 WebP 格式的字节流success, encoded_image = cv2.imencode('.webp', compressed_image, [int(cv2.IMWRITE_WEBP_QUALITY), 90])# 检查编码是否成功if success:compressed_bytes = encoded_image.tobytes()return compressed_byteselse:raise ValueError("Encoding image to WebP failed")except Exception as e:print(f"Error compressing image: {e}")return None
这种针对RGBA 类型的倒是能正常处理了,
但是针对RGB三通道的就有点不好了
如,原图:
用上面的方法压缩之后:
所以针对此类型的再优化一下:
def zip_img(image_bytes):'''压缩图片:param image_bytes: 原始图片的字节流:return: 压缩后的图片字节流'''try:# 将字节流转换为 NumPy 数组image_np = np.frombuffer(image_bytes, np.uint8)# 解码为图像,保留透明通道image = cv2.imdecode(image_np, cv2.IMREAD_UNCHANGED)if image is None:raise ValueError("Unable to decode the image")# 输入图像可能是 RGBA 或 RGBif image.shape[2] == 4: # RGBAprint("输入的图像是RGBA格式")# 分离通道b, g, r, a = cv2.split(image)# 创建一个白色背景background = np.ones((image.shape[0], image.shape[1], 3), dtype=np.uint8) * 255# 将前景(带有透明度的图像)叠加到白色背景上foreground = cv2.merge((b, g, r))alpha_mask = a.astype(float) / 255.0for c in range(3):background[..., c] = (alpha_mask * foreground[..., c] + (1 - alpha_mask) * background[..., c])image = background # 使用白色背景图像替换原图h, w, c = image.shapemax_size = 600ratio = min(1, min(max_size / h, max_size / w))# 缩放图像compressed_image = cv2.resize(image, (int(w * ratio), int(h * ratio)))# 将图像编码为 WebP 格式的字节流,设置压缩质量success, encoded_image = cv2.imencode('.webp', compressed_image, [int(cv2.IMWRITE_WEBP_QUALITY), 90])# 检查编码是否成功if success:compressed_bytes = encoded_image.tobytes()return compressed_byteselse:raise ValueError("Encoding image to WebP failed")except Exception as e:print(f"Error compressing image: {e}")return None
这样两种类型的都兼容了。
最后提供两种类型的图片url测试
# RGBA
image_url = 'https://img.vitkac.com/uploads/product_thumb/SUKIENKA%20M-ONERVAX%20A12396%200DLAX-9XX/lg/1.png'# RGB
image_url = "https://cdn.shopify.com/s/files/1/0020/4236/4017/files/ISNA-TOP-POWDER-BLUE-XO-HEART-WHTE-BINDA2.jpg?v=1719481642"
这篇关于图片压缩算法优化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!