display.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import os
  2. from PIL import Image
  3. def is_valid_image_path(image_path):
  4. """
  5. Checks if the image path is valid.
  6. Args:
  7. image_path: The path to the image.
  8. Returns:
  9. bool: True if the path is valid, False otherwise.
  10. """
  11. if not os.path.exists(image_path):
  12. return False
  13. # Check if the file extension is one of the common image formats.
  14. image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
  15. _, extension = os.path.splitext(image_path)
  16. if extension.lower() in image_extensions:
  17. return True
  18. else:
  19. return False
  20. def read_image(image_path, use_native=False):
  21. """
  22. Reads an image and resizes it while maintaining aspect ratio.
  23. Args:
  24. image_path: The path to the image.
  25. use_native: If True, the max dimension of the original image is used as the max size.
  26. If False, max size is set to 1024.
  27. Returns:
  28. tuple: (resized_image, original_width, original_height)
  29. """
  30. # Create a default 512x512 blue image as a fallback.
  31. image = Image.new('RGB', (512, 512), color=(0, 0, 255))
  32. if is_valid_image_path(image_path):
  33. image = Image.open(image_path)
  34. else:
  35. raise FileNotFoundError(f"{image_path}: Image path does not exist")
  36. w, h = image.size
  37. if use_native:
  38. max_size = max(w, h)
  39. else:
  40. max_size = 1024
  41. if w > h:
  42. new_w = max_size
  43. new_h = int(h * max_size / w)
  44. else:
  45. new_h = max_size
  46. new_w = int(w * max_size / h)
  47. image = image.resize((new_w, new_h))
  48. return image, w, h