test_image_compression_fix.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 测试图片压缩修复
  5. 验证修改后的压缩方法是否能成功将图片压缩到5000KB以内
  6. """
  7. import sys
  8. import os
  9. from io import BytesIO
  10. from PIL import Image
  11. import random
  12. # 添加项目根目录到Python路径
  13. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  14. from utils.minio.image_util import ImageUtil
  15. def create_large_test_image(width=3000, height=3000) -> BytesIO:
  16. """
  17. 创建一个大尺寸测试图片
  18. Args:
  19. width: 图片宽度
  20. height: 图片高度
  21. Returns:
  22. BytesIO: 大尺寸图片流
  23. """
  24. print(f"创建 {width}x{height} 的测试图片...")
  25. # 创建一个大尺寸图片,使用随机颜色填充
  26. img = Image.new('RGB', (width, height), color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
  27. # 将图片保存到BytesIO流
  28. img_stream = BytesIO()
  29. img.save(img_stream, format='PNG')
  30. img_stream.seek(0)
  31. # 检查图片大小
  32. img_stream.seek(0, 2)
  33. size_kb = img_stream.tell() / 1024
  34. img_stream.seek(0)
  35. print(f"测试图片创建完成,大小为 {size_kb:.2f}KB")
  36. return img_stream
  37. def test_image_compression():
  38. """
  39. 测试图片压缩方法
  40. """
  41. print("开始测试图片压缩方法...")
  42. # 创建ImageUtil实例
  43. image_util = ImageUtil()
  44. # 测试不同尺寸的图片压缩
  45. test_sizes = [
  46. (3000, 3000), # 约 25MB
  47. (4000, 4000), # 约 45MB
  48. (5000, 5000) # 约 70MB
  49. ]
  50. for width, height in test_sizes:
  51. print(f"\n=== 测试 {width}x{height} 图片压缩 ===")
  52. # 创建大尺寸测试图片
  53. img_stream = create_large_test_image(width, height)
  54. # 调用压缩方法
  55. compressed_stream = image_util._compress_image(img_stream, "test_large_image.png")
  56. # 检查压缩后的大小
  57. compressed_stream.seek(0, 2)
  58. compressed_size_kb = compressed_stream.tell() / 1024
  59. compressed_stream.seek(0)
  60. print(f"压缩后大小: {compressed_size_kb:.2f}KB")
  61. # 验证压缩结果
  62. if compressed_size_kb <= 5000:
  63. print("✅ 压缩成功!压缩后大小小于等于5000KB")
  64. else:
  65. print("❌ 压缩失败!压缩后大小仍大于5000KB")
  66. # 测试_compress_image_to_bytes方法
  67. print(f"\n=== 测试 _compress_image_to_bytes 方法 ===")
  68. img_stream = create_large_test_image(4000, 4000)
  69. compressed_bytes = image_util._compress_image_to_bytes(img_stream)
  70. compressed_size_kb = len(compressed_bytes) / 1024
  71. print(f"压缩后字节大小: {compressed_size_kb:.2f}KB")
  72. if compressed_size_kb <= 5000:
  73. print("✅ _compress_image_to_bytes 压缩成功!")
  74. else:
  75. print("❌ _compress_image_to_bytes 压缩失败!")
  76. print("\n=== 所有测试完成 ===")
  77. if __name__ == "__main__":
  78. test_image_compression()