图片压缩算法优化

正常的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 = 600
        ratio = 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_bytes
    except 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:  # RGBA
            print('RGBA')
            # 将 RGBA 转换为 BGRA
            image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA)
        elif image.shape[2] == 3:  # RGB
            # 将 RGB 转换为 BGR
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        h, w, c = image.shape
        max_size = 600
        ratio = 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_bytes
        else:
            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 或 RGB
        if image.shape[2] == 4:  # RGBA
            print("输入的图像是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.0
            for c in range(3):
                background[..., c] = (alpha_mask * foreground[..., c] + (1 - alpha_mask) * background[..., c])

            image = background  # 使用白色背景图像替换原图

        h, w, c = image.shape
        max_size = 600
        ratio = 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_bytes
        else:
            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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰履踏青云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值