No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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