test_save_quality.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import io
  2. import os
  3. from PIL import Image
  4. from sorawm.iopaint.helper import pil_to_bytes
  5. TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
  6. def test_jpeg_quality():
  7. # Test JPEG quality settings
  8. img_path = os.path.join(TESTS_DIR, "bunny.jpeg")
  9. pil_img = Image.open(img_path)
  10. # Test different quality settings
  11. high_quality = pil_to_bytes(pil_img, "jpg", quality=95)
  12. low_quality = pil_to_bytes(pil_img, "jpg", quality=50)
  13. # Print file sizes in KB
  14. print(f"High quality JPEG size: {len(high_quality) / 1024:.2f} KB")
  15. print(f"Low quality JPEG size: {len(low_quality) / 1024:.2f} KB")
  16. # Higher quality should result in larger file size
  17. assert len(high_quality) > len(low_quality)
  18. # Verify the output can be opened as an image
  19. Image.open(io.BytesIO(high_quality))
  20. Image.open(io.BytesIO(low_quality))
  21. def test_png_parameters():
  22. # Test PNG with parameters
  23. img_path = os.path.join(TESTS_DIR, "cat.png")
  24. pil_img = Image.open(img_path)
  25. # Test PNG with parameters
  26. params = {"parameters": "test_param=value"}
  27. png_with_params = pil_to_bytes(pil_img, "png", infos=params)
  28. # Test PNG without parameters
  29. png_without_params = pil_to_bytes(pil_img, "png")
  30. # Print file sizes in KB
  31. print(f"PNG with parameters size: {len(png_with_params) / 1024:.2f} KB")
  32. print(f"PNG without parameters size: {len(png_without_params) / 1024:.2f} KB")
  33. # Verify both outputs can be opened as images
  34. Image.open(io.BytesIO(png_with_params))
  35. Image.open(io.BytesIO(png_without_params))
  36. def test_format_conversion():
  37. # Test format conversion
  38. jpeg_path = os.path.join(TESTS_DIR, "bunny.jpeg")
  39. png_path = os.path.join(TESTS_DIR, "cat.png")
  40. # Convert JPEG to PNG
  41. jpeg_img = Image.open(jpeg_path)
  42. jpeg_to_png = pil_to_bytes(jpeg_img, "png")
  43. converted_png = Image.open(io.BytesIO(jpeg_to_png))
  44. print(f"JPEG to PNG size: {len(jpeg_to_png) / 1024:.2f} KB")
  45. assert converted_png.format.lower() == "png"
  46. # Convert PNG to JPEG
  47. png_img = Image.open(png_path)
  48. # Convert RGBA to RGB if necessary
  49. if png_img.mode == "RGBA":
  50. png_img = png_img.convert("RGB")
  51. png_to_jpeg = pil_to_bytes(png_img, "jpg")
  52. print(f"PNG to JPEG size: {len(png_to_jpeg) / 1024:.2f} KB")
  53. converted_jpeg = Image.open(io.BytesIO(png_to_jpeg))
  54. assert converted_jpeg.format.lower() == "jpeg"