| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- #!/usr/bin/env python3
- """
- 测试图片压缩到字节流功能
- """
- import os
- import sys
- from io import BytesIO
- from PIL import Image
- # 添加项目根目录到Python路径
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
- from utils.minio.image_util import image_util
- # 生成一个大的测试图片
- def generate_test_image(width=2000, height=2000, color=(255, 0, 0)):
- """
- 生成一个大的测试图片
- """
- print(f"生成测试图片,大小: {width}x{height}")
- img = Image.new('RGB', (width, height), color=color)
- img_stream = BytesIO()
- img.save(img_stream, format='PNG')
- img_stream.seek(0)
- return img_stream
- # 测试图片压缩到字节流功能
- def test_compress_image_bytes():
- """
- 测试图片压缩到字节流功能
- """
- print("开始测试图片压缩到字节流功能...")
-
- # 生成测试图片
- img_stream = generate_test_image()
-
- # 将图片流转换为字节流
- img_bytes = img_stream.getvalue()
- print(f"原始图片字节大小: {len(img_bytes)} 字节")
-
- # 调用压缩到字节流方法
- compressed_bytes = image_util.compress_image_bytes(img_bytes, max_size_kb=5000)
-
- # 检查压缩后大小
- compressed_size = len(compressed_bytes) / 1024
- print(f"压缩后大小: {compressed_size:.2f}KB")
-
- # 验证压缩后大小
- assert compressed_size <= 5000, f"压缩后大小 {compressed_size:.2f}KB 超过了最大限制 5000KB"
-
- # 验证返回类型
- assert isinstance(compressed_bytes, bytes), f"返回类型应为bytes,实际为 {type(compressed_bytes)}"
-
- print("图片压缩到字节流测试成功!")
- if __name__ == "__main__":
- test_compress_image_bytes()
|