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