欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > 图片压缩算法优化

图片压缩算法优化

2025/11/2 10:23:31 来源:https://blog.csdn.net/weixin_44327634/article/details/141724790  浏览:    关键词:图片压缩算法优化

正常的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"

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词