test_image_compression_bytes.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. """
  3. 测试图片压缩到字节流功能
  4. """
  5. import os
  6. import sys
  7. from io import BytesIO
  8. from PIL import Image
  9. # 添加项目根目录到Python路径
  10. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  11. from utils.minio.image_util import image_util
  12. # 生成一个大的测试图片
  13. def generate_test_image(width=2000, height=2000, color=(255, 0, 0)):
  14. """
  15. 生成一个大的测试图片
  16. """
  17. print(f"生成测试图片,大小: {width}x{height}")
  18. img = Image.new('RGB', (width, height), color=color)
  19. img_stream = BytesIO()
  20. img.save(img_stream, format='PNG')
  21. img_stream.seek(0)
  22. return img_stream
  23. # 测试图片压缩到字节流功能
  24. def test_image_compression_to_bytes():
  25. """
  26. 测试图片压缩到字节流功能
  27. """
  28. print("开始测试图片压缩到字节流功能...")
  29. # 生成测试图片
  30. img_stream = generate_test_image()
  31. # 检查压缩前大小
  32. img_stream.seek(0, 2)
  33. original_size = img_stream.tell() / 1024
  34. img_stream.seek(0)
  35. print(f"压缩前大小: {original_size:.2f}KB")
  36. # 调用压缩到字节流方法
  37. compressed_bytes = image_util._compress_image_to_bytes(img_stream, "test_image.png", max_size_kb=5000)
  38. # 检查压缩后大小
  39. compressed_size = len(compressed_bytes) / 1024
  40. print(f"压缩后大小: {compressed_size:.2f}KB")
  41. # 验证压缩后大小
  42. assert compressed_size <= 5000, f"压缩后大小 {compressed_size:.2f}KB 超过了最大限制 5000KB"
  43. # 验证返回类型
  44. assert isinstance(compressed_bytes, bytes), f"返回类型应为bytes,实际为 {type(compressed_bytes)}"
  45. print("图片压缩到字节流测试成功!")
  46. if __name__ == "__main__":
  47. test_image_compression_to_bytes()