You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

222 lines
8.2 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2020-2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from io import BytesIO
  17. from types import TracebackType
  18. from typing import Optional, Tuple, Type
  19. from PIL import Image
  20. logger = logging.getLogger(__name__)
  21. EXIF_ORIENTATION_TAG = 0x0112
  22. EXIF_TRANSPOSE_MAPPINGS = {
  23. 2: Image.FLIP_LEFT_RIGHT,
  24. 3: Image.ROTATE_180,
  25. 4: Image.FLIP_TOP_BOTTOM,
  26. 5: Image.TRANSPOSE,
  27. 6: Image.ROTATE_270,
  28. 7: Image.TRANSVERSE,
  29. 8: Image.ROTATE_90,
  30. }
  31. class ThumbnailError(Exception):
  32. """An error occurred generating a thumbnail."""
  33. class Thumbnailer:
  34. FORMATS = {"image/jpeg": "JPEG", "image/png": "PNG"}
  35. @staticmethod
  36. def set_limits(max_image_pixels: int) -> None:
  37. Image.MAX_IMAGE_PIXELS = max_image_pixels
  38. def __init__(self, input_path: str):
  39. # Have we closed the image?
  40. self._closed = False
  41. try:
  42. self.image = Image.open(input_path)
  43. except OSError as e:
  44. # If an error occurs opening the image, a thumbnail won't be able to
  45. # be generated.
  46. raise ThumbnailError from e
  47. except Image.DecompressionBombError as e:
  48. # If an image decompression bomb error occurs opening the image,
  49. # then the image exceeds the pixel limit and a thumbnail won't
  50. # be able to be generated.
  51. raise ThumbnailError from e
  52. self.width, self.height = self.image.size
  53. self.transpose_method = None
  54. try:
  55. # We don't use ImageOps.exif_transpose since it crashes with big EXIF
  56. #
  57. # Ignore safety: Pillow seems to acknowledge that this method is
  58. # "private, experimental, but generally widely used". Pillow 6
  59. # includes a public getexif() method (no underscore) that we might
  60. # consider using instead when we can bump that dependency.
  61. #
  62. # At the time of writing, Debian buster (currently oldstable)
  63. # provides version 5.4.1. It's expected to EOL in mid-2022, see
  64. # https://wiki.debian.org/DebianReleases#Production_Releases
  65. image_exif = self.image._getexif() # type: ignore
  66. if image_exif is not None:
  67. image_orientation = image_exif.get(EXIF_ORIENTATION_TAG)
  68. assert type(image_orientation) is int
  69. self.transpose_method = EXIF_TRANSPOSE_MAPPINGS.get(image_orientation)
  70. except Exception as e:
  71. # A lot of parsing errors can happen when parsing EXIF
  72. logger.info("Error parsing image EXIF information: %s", e)
  73. def transpose(self) -> Tuple[int, int]:
  74. """Transpose the image using its EXIF Orientation tag
  75. Returns:
  76. A tuple containing the new image size in pixels as (width, height).
  77. """
  78. if self.transpose_method is not None:
  79. # Safety: `transpose` takes an int rather than e.g. an IntEnum.
  80. # self.transpose_method is set above to be a value in
  81. # EXIF_TRANSPOSE_MAPPINGS, and that only contains correct values.
  82. with self.image:
  83. self.image = self.image.transpose(self.transpose_method) # type: ignore[arg-type]
  84. self.width, self.height = self.image.size
  85. self.transpose_method = None
  86. # We don't need EXIF any more
  87. self.image.info["exif"] = None
  88. return self.image.size
  89. def aspect(self, max_width: int, max_height: int) -> Tuple[int, int]:
  90. """Calculate the largest size that preserves aspect ratio which
  91. fits within the given rectangle::
  92. (w_in / h_in) = (w_out / h_out)
  93. w_out = max(min(w_max, h_max * (w_in / h_in)), 1)
  94. h_out = max(min(h_max, w_max * (h_in / w_in)), 1)
  95. Args:
  96. max_width: The largest possible width.
  97. max_height: The largest possible height.
  98. """
  99. if max_width * self.height < max_height * self.width:
  100. return max_width, max((max_width * self.height) // self.width, 1)
  101. else:
  102. return max((max_height * self.width) // self.height, 1), max_height
  103. def _resize(self, width: int, height: int) -> Image.Image:
  104. # 1-bit or 8-bit color palette images need converting to RGB
  105. # otherwise they will be scaled using nearest neighbour which
  106. # looks awful.
  107. #
  108. # If the image has transparency, use RGBA instead.
  109. if self.image.mode in ["1", "L", "P"]:
  110. if self.image.info.get("transparency", None) is not None:
  111. with self.image:
  112. self.image = self.image.convert("RGBA")
  113. else:
  114. with self.image:
  115. self.image = self.image.convert("RGB")
  116. return self.image.resize((width, height), Image.ANTIALIAS)
  117. def scale(self, width: int, height: int, output_type: str) -> BytesIO:
  118. """Rescales the image to the given dimensions.
  119. Returns:
  120. The bytes of the encoded image ready to be written to disk
  121. """
  122. with self._resize(width, height) as scaled:
  123. return self._encode_image(scaled, output_type)
  124. def crop(self, width: int, height: int, output_type: str) -> BytesIO:
  125. """Rescales and crops the image to the given dimensions preserving
  126. aspect::
  127. (w_in / h_in) = (w_scaled / h_scaled)
  128. w_scaled = max(w_out, h_out * (w_in / h_in))
  129. h_scaled = max(h_out, w_out * (h_in / w_in))
  130. Args:
  131. max_width: The largest possible width.
  132. max_height: The largest possible height.
  133. Returns:
  134. The bytes of the encoded image ready to be written to disk
  135. """
  136. if width * self.height > height * self.width:
  137. scaled_width = width
  138. scaled_height = (width * self.height) // self.width
  139. crop_top = (scaled_height - height) // 2
  140. crop_bottom = height + crop_top
  141. crop = (0, crop_top, width, crop_bottom)
  142. else:
  143. scaled_width = (height * self.width) // self.height
  144. scaled_height = height
  145. crop_left = (scaled_width - width) // 2
  146. crop_right = width + crop_left
  147. crop = (crop_left, 0, crop_right, height)
  148. with self._resize(scaled_width, scaled_height) as scaled_image:
  149. with scaled_image.crop(crop) as cropped:
  150. return self._encode_image(cropped, output_type)
  151. def _encode_image(self, output_image: Image.Image, output_type: str) -> BytesIO:
  152. output_bytes_io = BytesIO()
  153. fmt = self.FORMATS[output_type]
  154. if fmt == "JPEG":
  155. output_image = output_image.convert("RGB")
  156. output_image.save(output_bytes_io, fmt, quality=80)
  157. return output_bytes_io
  158. def close(self) -> None:
  159. """Closes the underlying image file.
  160. Once closed no other functions can be called.
  161. Can be called multiple times.
  162. """
  163. if self._closed:
  164. return
  165. self._closed = True
  166. # Since we run this on the finalizer then we need to handle `__init__`
  167. # raising an exception before it can define `self.image`.
  168. image = getattr(self, "image", None)
  169. if image is None:
  170. return
  171. image.close()
  172. def __enter__(self) -> "Thumbnailer":
  173. """Make `Thumbnailer` a context manager that calls `close` on
  174. `__exit__`.
  175. """
  176. return self
  177. def __exit__(
  178. self,
  179. type: Optional[Type[BaseException]],
  180. value: Optional[BaseException],
  181. traceback: Optional[TracebackType],
  182. ) -> None:
  183. self.close()
  184. def __del__(self) -> None:
  185. # Make sure we actually do close the image, rather than leak data.
  186. self.close()