ImageOps.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # standard image operations
  6. #
  7. # History:
  8. # 2001-10-20 fl Created
  9. # 2001-10-23 fl Added autocontrast operator
  10. # 2001-12-18 fl Added Kevin's fit operator
  11. # 2004-03-14 fl Fixed potential division by zero in equalize
  12. # 2005-05-05 fl Fixed equalize for low number of values
  13. #
  14. # Copyright (c) 2001-2004 by Secret Labs AB
  15. # Copyright (c) 2001-2004 by Fredrik Lundh
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. from __future__ import annotations
  20. import functools
  21. import operator
  22. import re
  23. from collections.abc import Sequence
  24. from typing import Protocol, cast
  25. from . import ExifTags, Image, ImagePalette
  26. #
  27. # helpers
  28. def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
  29. if isinstance(border, tuple):
  30. if len(border) == 2:
  31. left, top = right, bottom = border
  32. elif len(border) == 4:
  33. left, top, right, bottom = border
  34. else:
  35. left = top = right = bottom = border
  36. return left, top, right, bottom
  37. def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
  38. if isinstance(color, str):
  39. from . import ImageColor
  40. color = ImageColor.getcolor(color, mode)
  41. return color
  42. def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
  43. if image.mode == "P":
  44. # FIXME: apply to lookup table, not image data
  45. msg = "mode P support coming soon"
  46. raise NotImplementedError(msg)
  47. elif image.mode in ("L", "RGB"):
  48. if image.mode == "RGB" and len(lut) == 256:
  49. lut = lut + lut + lut
  50. return image.point(lut)
  51. else:
  52. msg = f"not supported for mode {image.mode}"
  53. raise OSError(msg)
  54. #
  55. # actions
  56. def autocontrast(
  57. image: Image.Image,
  58. cutoff: float | tuple[float, float] = 0,
  59. ignore: int | Sequence[int] | None = None,
  60. mask: Image.Image | None = None,
  61. preserve_tone: bool = False,
  62. ) -> Image.Image:
  63. """
  64. Maximize (normalize) image contrast. This function calculates a
  65. histogram of the input image (or mask region), removes ``cutoff`` percent of the
  66. lightest and darkest pixels from the histogram, and remaps the image
  67. so that the darkest pixel becomes black (0), and the lightest
  68. becomes white (255).
  69. :param image: The image to process.
  70. :param cutoff: The percent to cut off from the histogram on the low and
  71. high ends. Either a tuple of (low, high), or a single
  72. number for both.
  73. :param ignore: The background pixel value (use None for no background).
  74. :param mask: Histogram used in contrast operation is computed using pixels
  75. within the mask. If no mask is given the entire image is used
  76. for histogram computation.
  77. :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
  78. .. versionadded:: 8.2.0
  79. :return: An image.
  80. """
  81. if preserve_tone:
  82. histogram = image.convert("L").histogram(mask)
  83. else:
  84. histogram = image.histogram(mask)
  85. lut = []
  86. for layer in range(0, len(histogram), 256):
  87. h = histogram[layer : layer + 256]
  88. if ignore is not None:
  89. # get rid of outliers
  90. if isinstance(ignore, int):
  91. h[ignore] = 0
  92. else:
  93. for ix in ignore:
  94. h[ix] = 0
  95. if cutoff:
  96. # cut off pixels from both ends of the histogram
  97. if not isinstance(cutoff, tuple):
  98. cutoff = (cutoff, cutoff)
  99. # get number of pixels
  100. n = 0
  101. for ix in range(256):
  102. n = n + h[ix]
  103. # remove cutoff% pixels from the low end
  104. cut = int(n * cutoff[0] // 100)
  105. for lo in range(256):
  106. if cut > h[lo]:
  107. cut = cut - h[lo]
  108. h[lo] = 0
  109. else:
  110. h[lo] -= cut
  111. cut = 0
  112. if cut <= 0:
  113. break
  114. # remove cutoff% samples from the high end
  115. cut = int(n * cutoff[1] // 100)
  116. for hi in range(255, -1, -1):
  117. if cut > h[hi]:
  118. cut = cut - h[hi]
  119. h[hi] = 0
  120. else:
  121. h[hi] -= cut
  122. cut = 0
  123. if cut <= 0:
  124. break
  125. # find lowest/highest samples after preprocessing
  126. for lo in range(256):
  127. if h[lo]:
  128. break
  129. for hi in range(255, -1, -1):
  130. if h[hi]:
  131. break
  132. if hi <= lo:
  133. # don't bother
  134. lut.extend(list(range(256)))
  135. else:
  136. scale = 255.0 / (hi - lo)
  137. offset = -lo * scale
  138. for ix in range(256):
  139. ix = int(ix * scale + offset)
  140. if ix < 0:
  141. ix = 0
  142. elif ix > 255:
  143. ix = 255
  144. lut.append(ix)
  145. return _lut(image, lut)
  146. def colorize(
  147. image: Image.Image,
  148. black: str | tuple[int, ...],
  149. white: str | tuple[int, ...],
  150. mid: str | int | tuple[int, ...] | None = None,
  151. blackpoint: int = 0,
  152. whitepoint: int = 255,
  153. midpoint: int = 127,
  154. ) -> Image.Image:
  155. """
  156. Colorize grayscale image.
  157. This function calculates a color wedge which maps all black pixels in
  158. the source image to the first color and all white pixels to the
  159. second color. If ``mid`` is specified, it uses three-color mapping.
  160. The ``black`` and ``white`` arguments should be RGB tuples or color names;
  161. optionally you can use three-color mapping by also specifying ``mid``.
  162. Mapping positions for any of the colors can be specified
  163. (e.g. ``blackpoint``), where these parameters are the integer
  164. value corresponding to where the corresponding color should be mapped.
  165. These parameters must have logical order, such that
  166. ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
  167. :param image: The image to colorize.
  168. :param black: The color to use for black input pixels.
  169. :param white: The color to use for white input pixels.
  170. :param mid: The color to use for midtone input pixels.
  171. :param blackpoint: an int value [0, 255] for the black mapping.
  172. :param whitepoint: an int value [0, 255] for the white mapping.
  173. :param midpoint: an int value [0, 255] for the midtone mapping.
  174. :return: An image.
  175. """
  176. # Initial asserts
  177. assert image.mode == "L"
  178. if mid is None:
  179. assert 0 <= blackpoint <= whitepoint <= 255
  180. else:
  181. assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
  182. # Define colors from arguments
  183. rgb_black = cast(Sequence[int], _color(black, "RGB"))
  184. rgb_white = cast(Sequence[int], _color(white, "RGB"))
  185. rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
  186. # Empty lists for the mapping
  187. red = []
  188. green = []
  189. blue = []
  190. # Create the low-end values
  191. for i in range(0, blackpoint):
  192. red.append(rgb_black[0])
  193. green.append(rgb_black[1])
  194. blue.append(rgb_black[2])
  195. # Create the mapping (2-color)
  196. if rgb_mid is None:
  197. range_map = range(0, whitepoint - blackpoint)
  198. for i in range_map:
  199. red.append(
  200. rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
  201. )
  202. green.append(
  203. rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
  204. )
  205. blue.append(
  206. rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
  207. )
  208. # Create the mapping (3-color)
  209. else:
  210. range_map1 = range(0, midpoint - blackpoint)
  211. range_map2 = range(0, whitepoint - midpoint)
  212. for i in range_map1:
  213. red.append(
  214. rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
  215. )
  216. green.append(
  217. rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
  218. )
  219. blue.append(
  220. rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
  221. )
  222. for i in range_map2:
  223. red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
  224. green.append(
  225. rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
  226. )
  227. blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
  228. # Create the high-end values
  229. for i in range(0, 256 - whitepoint):
  230. red.append(rgb_white[0])
  231. green.append(rgb_white[1])
  232. blue.append(rgb_white[2])
  233. # Return converted image
  234. image = image.convert("RGB")
  235. return _lut(image, red + green + blue)
  236. def contain(
  237. image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
  238. ) -> Image.Image:
  239. """
  240. Returns a resized version of the image, set to the maximum width and height
  241. within the requested size, while maintaining the original aspect ratio.
  242. :param image: The image to resize.
  243. :param size: The requested output size in pixels, given as a
  244. (width, height) tuple.
  245. :param method: Resampling method to use. Default is
  246. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  247. See :ref:`concept-filters`.
  248. :return: An image.
  249. """
  250. im_ratio = image.width / image.height
  251. dest_ratio = size[0] / size[1]
  252. if im_ratio != dest_ratio:
  253. if im_ratio > dest_ratio:
  254. new_height = round(image.height / image.width * size[0])
  255. if new_height != size[1]:
  256. size = (size[0], new_height)
  257. else:
  258. new_width = round(image.width / image.height * size[1])
  259. if new_width != size[0]:
  260. size = (new_width, size[1])
  261. return image.resize(size, resample=method)
  262. def cover(
  263. image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
  264. ) -> Image.Image:
  265. """
  266. Returns a resized version of the image, so that the requested size is
  267. covered, while maintaining the original aspect ratio.
  268. :param image: The image to resize.
  269. :param size: The requested output size in pixels, given as a
  270. (width, height) tuple.
  271. :param method: Resampling method to use. Default is
  272. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  273. See :ref:`concept-filters`.
  274. :return: An image.
  275. """
  276. im_ratio = image.width / image.height
  277. dest_ratio = size[0] / size[1]
  278. if im_ratio != dest_ratio:
  279. if im_ratio < dest_ratio:
  280. new_height = round(image.height / image.width * size[0])
  281. if new_height != size[1]:
  282. size = (size[0], new_height)
  283. else:
  284. new_width = round(image.width / image.height * size[1])
  285. if new_width != size[0]:
  286. size = (new_width, size[1])
  287. return image.resize(size, resample=method)
  288. def pad(
  289. image: Image.Image,
  290. size: tuple[int, int],
  291. method: int = Image.Resampling.BICUBIC,
  292. color: str | int | tuple[int, ...] | None = None,
  293. centering: tuple[float, float] = (0.5, 0.5),
  294. ) -> Image.Image:
  295. """
  296. Returns a resized and padded version of the image, expanded to fill the
  297. requested aspect ratio and size.
  298. :param image: The image to resize and crop.
  299. :param size: The requested output size in pixels, given as a
  300. (width, height) tuple.
  301. :param method: Resampling method to use. Default is
  302. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  303. See :ref:`concept-filters`.
  304. :param color: The background color of the padded image.
  305. :param centering: Control the position of the original image within the
  306. padded version.
  307. (0.5, 0.5) will keep the image centered
  308. (0, 0) will keep the image aligned to the top left
  309. (1, 1) will keep the image aligned to the bottom
  310. right
  311. :return: An image.
  312. """
  313. resized = contain(image, size, method)
  314. if resized.size == size:
  315. out = resized
  316. else:
  317. out = Image.new(image.mode, size, color)
  318. if resized.palette:
  319. palette = resized.getpalette()
  320. if palette is not None:
  321. out.putpalette(palette)
  322. if resized.width != size[0]:
  323. x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
  324. out.paste(resized, (x, 0))
  325. else:
  326. y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
  327. out.paste(resized, (0, y))
  328. return out
  329. def crop(image: Image.Image, border: int = 0) -> Image.Image:
  330. """
  331. Remove border from image. The same amount of pixels are removed
  332. from all four sides. This function works on all image modes.
  333. .. seealso:: :py:meth:`~PIL.Image.Image.crop`
  334. :param image: The image to crop.
  335. :param border: The number of pixels to remove.
  336. :return: An image.
  337. """
  338. left, top, right, bottom = _border(border)
  339. return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
  340. def scale(
  341. image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
  342. ) -> Image.Image:
  343. """
  344. Returns a rescaled image by a specific factor given in parameter.
  345. A factor greater than 1 expands the image, between 0 and 1 contracts the
  346. image.
  347. :param image: The image to rescale.
  348. :param factor: The expansion factor, as a float.
  349. :param resample: Resampling method to use. Default is
  350. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  351. See :ref:`concept-filters`.
  352. :returns: An :py:class:`~PIL.Image.Image` object.
  353. """
  354. if factor == 1:
  355. return image.copy()
  356. elif factor <= 0:
  357. msg = "the factor must be greater than 0"
  358. raise ValueError(msg)
  359. else:
  360. size = (round(factor * image.width), round(factor * image.height))
  361. return image.resize(size, resample)
  362. class SupportsGetMesh(Protocol):
  363. """
  364. An object that supports the ``getmesh`` method, taking an image as an
  365. argument, and returning a list of tuples. Each tuple contains two tuples,
  366. the source box as a tuple of 4 integers, and a tuple of 8 integers for the
  367. final quadrilateral, in order of top left, bottom left, bottom right, top
  368. right.
  369. """
  370. def getmesh(
  371. self, image: Image.Image
  372. ) -> list[
  373. tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
  374. ]: ...
  375. def deform(
  376. image: Image.Image,
  377. deformer: SupportsGetMesh,
  378. resample: int = Image.Resampling.BILINEAR,
  379. ) -> Image.Image:
  380. """
  381. Deform the image.
  382. :param image: The image to deform.
  383. :param deformer: A deformer object. Any object that implements a
  384. ``getmesh`` method can be used.
  385. :param resample: An optional resampling filter. Same values possible as
  386. in the PIL.Image.transform function.
  387. :return: An image.
  388. """
  389. return image.transform(
  390. image.size, Image.Transform.MESH, deformer.getmesh(image), resample
  391. )
  392. def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
  393. """
  394. Equalize the image histogram. This function applies a non-linear
  395. mapping to the input image, in order to create a uniform
  396. distribution of grayscale values in the output image.
  397. :param image: The image to equalize.
  398. :param mask: An optional mask. If given, only the pixels selected by
  399. the mask are included in the analysis.
  400. :return: An image.
  401. """
  402. if image.mode == "P":
  403. image = image.convert("RGB")
  404. h = image.histogram(mask)
  405. lut = []
  406. for b in range(0, len(h), 256):
  407. histo = [_f for _f in h[b : b + 256] if _f]
  408. if len(histo) <= 1:
  409. lut.extend(list(range(256)))
  410. else:
  411. step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
  412. if not step:
  413. lut.extend(list(range(256)))
  414. else:
  415. n = step // 2
  416. for i in range(256):
  417. lut.append(n // step)
  418. n = n + h[i + b]
  419. return _lut(image, lut)
  420. def expand(
  421. image: Image.Image,
  422. border: int | tuple[int, ...] = 0,
  423. fill: str | int | tuple[int, ...] = 0,
  424. ) -> Image.Image:
  425. """
  426. Add border to the image
  427. :param image: The image to expand.
  428. :param border: Border width, in pixels.
  429. :param fill: Pixel fill value (a color value). Default is 0 (black).
  430. :return: An image.
  431. """
  432. left, top, right, bottom = _border(border)
  433. width = left + image.size[0] + right
  434. height = top + image.size[1] + bottom
  435. color = _color(fill, image.mode)
  436. if image.palette:
  437. palette = ImagePalette.ImagePalette(palette=image.getpalette())
  438. if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
  439. color = palette.getcolor(color)
  440. else:
  441. palette = None
  442. out = Image.new(image.mode, (width, height), color)
  443. if palette:
  444. out.putpalette(palette.palette)
  445. out.paste(image, (left, top))
  446. return out
  447. def fit(
  448. image: Image.Image,
  449. size: tuple[int, int],
  450. method: int = Image.Resampling.BICUBIC,
  451. bleed: float = 0.0,
  452. centering: tuple[float, float] = (0.5, 0.5),
  453. ) -> Image.Image:
  454. """
  455. Returns a resized and cropped version of the image, cropped to the
  456. requested aspect ratio and size.
  457. This function was contributed by Kevin Cazabon.
  458. :param image: The image to resize and crop.
  459. :param size: The requested output size in pixels, given as a
  460. (width, height) tuple.
  461. :param method: Resampling method to use. Default is
  462. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  463. See :ref:`concept-filters`.
  464. :param bleed: Remove a border around the outside of the image from all
  465. four edges. The value is a decimal percentage (use 0.01 for
  466. one percent). The default value is 0 (no border).
  467. Cannot be greater than or equal to 0.5.
  468. :param centering: Control the cropping position. Use (0.5, 0.5) for
  469. center cropping (e.g. if cropping the width, take 50% off
  470. of the left side, and therefore 50% off the right side).
  471. (0.0, 0.0) will crop from the top left corner (i.e. if
  472. cropping the width, take all of the crop off of the right
  473. side, and if cropping the height, take all of it off the
  474. bottom). (1.0, 0.0) will crop from the bottom left
  475. corner, etc. (i.e. if cropping the width, take all of the
  476. crop off the left side, and if cropping the height take
  477. none from the top, and therefore all off the bottom).
  478. :return: An image.
  479. """
  480. # by Kevin Cazabon, Feb 17/2000
  481. # kevin@cazabon.com
  482. # https://www.cazabon.com
  483. centering_x, centering_y = centering
  484. if not 0.0 <= centering_x <= 1.0:
  485. centering_x = 0.5
  486. if not 0.0 <= centering_y <= 1.0:
  487. centering_y = 0.5
  488. if not 0.0 <= bleed < 0.5:
  489. bleed = 0.0
  490. # calculate the area to use for resizing and cropping, subtracting
  491. # the 'bleed' around the edges
  492. # number of pixels to trim off on Top and Bottom, Left and Right
  493. bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
  494. live_size = (
  495. image.size[0] - bleed_pixels[0] * 2,
  496. image.size[1] - bleed_pixels[1] * 2,
  497. )
  498. # calculate the aspect ratio of the live_size
  499. live_size_ratio = live_size[0] / live_size[1]
  500. # calculate the aspect ratio of the output image
  501. output_ratio = size[0] / size[1]
  502. # figure out if the sides or top/bottom will be cropped off
  503. if live_size_ratio == output_ratio:
  504. # live_size is already the needed ratio
  505. crop_width = live_size[0]
  506. crop_height = live_size[1]
  507. elif live_size_ratio >= output_ratio:
  508. # live_size is wider than what's needed, crop the sides
  509. crop_width = output_ratio * live_size[1]
  510. crop_height = live_size[1]
  511. else:
  512. # live_size is taller than what's needed, crop the top and bottom
  513. crop_width = live_size[0]
  514. crop_height = live_size[0] / output_ratio
  515. # make the crop
  516. crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
  517. crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
  518. crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
  519. # resize the image and return it
  520. return image.resize(size, method, box=crop)
  521. def flip(image: Image.Image) -> Image.Image:
  522. """
  523. Flip the image vertically (top to bottom).
  524. :param image: The image to flip.
  525. :return: An image.
  526. """
  527. return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
  528. def grayscale(image: Image.Image) -> Image.Image:
  529. """
  530. Convert the image to grayscale.
  531. :param image: The image to convert.
  532. :return: An image.
  533. """
  534. return image.convert("L")
  535. def invert(image: Image.Image) -> Image.Image:
  536. """
  537. Invert (negate) the image.
  538. :param image: The image to invert.
  539. :return: An image.
  540. """
  541. lut = list(range(255, -1, -1))
  542. return image.point(lut) if image.mode == "1" else _lut(image, lut)
  543. def mirror(image: Image.Image) -> Image.Image:
  544. """
  545. Flip image horizontally (left to right).
  546. :param image: The image to mirror.
  547. :return: An image.
  548. """
  549. return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  550. def posterize(image: Image.Image, bits: int) -> Image.Image:
  551. """
  552. Reduce the number of bits for each color channel.
  553. :param image: The image to posterize.
  554. :param bits: The number of bits to keep for each channel (1-8).
  555. :return: An image.
  556. """
  557. mask = ~(2 ** (8 - bits) - 1)
  558. lut = [i & mask for i in range(256)]
  559. return _lut(image, lut)
  560. def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
  561. """
  562. Invert all pixel values above a threshold.
  563. :param image: The image to solarize.
  564. :param threshold: All pixels above this grayscale level are inverted.
  565. :return: An image.
  566. """
  567. lut = []
  568. for i in range(256):
  569. if i < threshold:
  570. lut.append(i)
  571. else:
  572. lut.append(255 - i)
  573. return _lut(image, lut)
  574. def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
  575. """
  576. If an image has an EXIF Orientation tag, other than 1, transpose the image
  577. accordingly, and remove the orientation data.
  578. :param image: The image to transpose.
  579. :param in_place: Boolean. Keyword-only argument.
  580. If ``True``, the original image is modified in-place, and ``None`` is returned.
  581. If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
  582. with the transposition applied. If there is no transposition, a copy of the
  583. image will be returned.
  584. """
  585. image.load()
  586. image_exif = image.getexif()
  587. orientation = image_exif.get(ExifTags.Base.Orientation, 1)
  588. method = {
  589. 2: Image.Transpose.FLIP_LEFT_RIGHT,
  590. 3: Image.Transpose.ROTATE_180,
  591. 4: Image.Transpose.FLIP_TOP_BOTTOM,
  592. 5: Image.Transpose.TRANSPOSE,
  593. 6: Image.Transpose.ROTATE_270,
  594. 7: Image.Transpose.TRANSVERSE,
  595. 8: Image.Transpose.ROTATE_90,
  596. }.get(orientation)
  597. if method is not None:
  598. if in_place:
  599. image.im = image.im.transpose(method)
  600. image._size = image.im.size
  601. else:
  602. transposed_image = image.transpose(method)
  603. exif_image = image if in_place else transposed_image
  604. exif = exif_image.getexif()
  605. if ExifTags.Base.Orientation in exif:
  606. del exif[ExifTags.Base.Orientation]
  607. if "exif" in exif_image.info:
  608. exif_image.info["exif"] = exif.tobytes()
  609. elif "Raw profile type exif" in exif_image.info:
  610. exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
  611. for key in ("XML:com.adobe.xmp", "xmp"):
  612. if key in exif_image.info:
  613. for pattern in (
  614. r'tiff:Orientation="([0-9])"',
  615. r"<tiff:Orientation>([0-9])</tiff:Orientation>",
  616. ):
  617. value = exif_image.info[key]
  618. exif_image.info[key] = (
  619. re.sub(pattern, "", value)
  620. if isinstance(value, str)
  621. else re.sub(pattern.encode(), b"", value)
  622. )
  623. if not in_place:
  624. return transposed_image
  625. elif not in_place:
  626. return image.copy()
  627. return None