TiffImagePlugin.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # TIFF file handling
  6. #
  7. # TIFF is a flexible, if somewhat aged, image file format originally
  8. # defined by Aldus. Although TIFF supports a wide variety of pixel
  9. # layouts and compression methods, the name doesn't really stand for
  10. # "thousands of incompatible file formats," it just feels that way.
  11. #
  12. # To read TIFF data from a stream, the stream must be seekable. For
  13. # progressive decoding, make sure to use TIFF files where the tag
  14. # directory is placed first in the file.
  15. #
  16. # History:
  17. # 1995-09-01 fl Created
  18. # 1996-05-04 fl Handle JPEGTABLES tag
  19. # 1996-05-18 fl Fixed COLORMAP support
  20. # 1997-01-05 fl Fixed PREDICTOR support
  21. # 1997-08-27 fl Added support for rational tags (from Perry Stoll)
  22. # 1998-01-10 fl Fixed seek/tell (from Jan Blom)
  23. # 1998-07-15 fl Use private names for internal variables
  24. # 1999-06-13 fl Rewritten for PIL 1.0 (1.0)
  25. # 2000-10-11 fl Additional fixes for Python 2.0 (1.1)
  26. # 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2)
  27. # 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3)
  28. # 2001-12-18 fl Added workaround for broken Matrox library
  29. # 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart)
  30. # 2003-05-19 fl Check FILLORDER tag
  31. # 2003-09-26 fl Added RGBa support
  32. # 2004-02-24 fl Added DPI support; fixed rational write support
  33. # 2005-02-07 fl Added workaround for broken Corel Draw 10 files
  34. # 2006-01-09 fl Added support for float/double tags (from Russell Nelson)
  35. #
  36. # Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved.
  37. # Copyright (c) 1995-1997 by Fredrik Lundh
  38. #
  39. # See the README file for information on usage and redistribution.
  40. #
  41. from __future__ import annotations
  42. __lazy_modules__ = {
  43. "PIL._binary",
  44. "PIL._util",
  45. "fractions",
  46. "itertools",
  47. "math",
  48. "struct",
  49. "warnings",
  50. }
  51. import io
  52. import itertools
  53. import logging
  54. import math
  55. import os
  56. import struct
  57. import warnings
  58. from collections.abc import Callable, MutableMapping
  59. from fractions import Fraction
  60. from numbers import Number, Rational
  61. from typing import IO, Any, cast
  62. from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags
  63. from ._binary import i16be as i16
  64. from ._binary import i32be as i32
  65. from ._util import DeferredError, is_path
  66. from .TiffTags import TYPES
  67. TYPE_CHECKING = False
  68. if TYPE_CHECKING:
  69. from collections.abc import Iterator
  70. from typing import NoReturn, Self
  71. from ._typing import Buffer, IntegralLike, StrOrBytesPath
  72. logger = logging.getLogger(__name__)
  73. # Set these to true to force use of libtiff for reading or writing.
  74. READ_LIBTIFF = False
  75. WRITE_LIBTIFF = False
  76. STRIP_SIZE = 65536
  77. II = b"II" # little-endian (Intel style)
  78. MM = b"MM" # big-endian (Motorola style)
  79. #
  80. # --------------------------------------------------------------------
  81. # Read TIFF files
  82. # a few tag names, just to make the code below a bit more readable
  83. OSUBFILETYPE = 255
  84. IMAGEWIDTH = 256
  85. IMAGELENGTH = 257
  86. BITSPERSAMPLE = 258
  87. COMPRESSION = 259
  88. PHOTOMETRIC_INTERPRETATION = 262
  89. FILLORDER = 266
  90. IMAGEDESCRIPTION = 270
  91. STRIPOFFSETS = 273
  92. SAMPLESPERPIXEL = 277
  93. ROWSPERSTRIP = 278
  94. STRIPBYTECOUNTS = 279
  95. X_RESOLUTION = 282
  96. Y_RESOLUTION = 283
  97. PLANAR_CONFIGURATION = 284
  98. RESOLUTION_UNIT = 296
  99. TRANSFERFUNCTION = 301
  100. SOFTWARE = 305
  101. DATE_TIME = 306
  102. ARTIST = 315
  103. PREDICTOR = 317
  104. COLORMAP = 320
  105. TILEWIDTH = 322
  106. TILELENGTH = 323
  107. TILEOFFSETS = 324
  108. TILEBYTECOUNTS = 325
  109. SUBIFD = 330
  110. EXTRASAMPLES = 338
  111. SAMPLEFORMAT = 339
  112. JPEGTABLES = 347
  113. YCBCRSUBSAMPLING = 530
  114. REFERENCEBLACKWHITE = 532
  115. COPYRIGHT = 33432
  116. IPTC_NAA_CHUNK = 33723 # newsphoto properties
  117. PHOTOSHOP_CHUNK = 34377 # photoshop properties
  118. ICCPROFILE = 34675
  119. EXIFIFD = 34665
  120. XMP = 700
  121. JPEGQUALITY = 65537 # pseudo-tag by libtiff
  122. # https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
  123. IMAGEJ_META_DATA_BYTE_COUNTS = 50838
  124. IMAGEJ_META_DATA = 50839
  125. COMPRESSION_INFO = {
  126. # Compression => pil compression name
  127. 1: "raw",
  128. 2: "tiff_ccitt",
  129. 3: "group3",
  130. 4: "group4",
  131. 5: "tiff_lzw",
  132. 6: "tiff_jpeg", # obsolete
  133. 7: "jpeg",
  134. 8: "tiff_adobe_deflate",
  135. 32771: "tiff_raw_16", # 16-bit padding
  136. 32773: "packbits",
  137. 32809: "tiff_thunderscan",
  138. 32946: "tiff_deflate",
  139. 34676: "tiff_sgilog",
  140. 34677: "tiff_sgilog24",
  141. 34925: "lzma",
  142. 50000: "zstd",
  143. 50001: "webp",
  144. }
  145. COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}
  146. OPEN_INFO = {
  147. # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
  148. # ExtraSamples) => mode, rawmode
  149. (II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
  150. (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
  151. (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
  152. (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
  153. (II, 1, (1,), 1, (1,), ()): ("1", "1"),
  154. (MM, 1, (1,), 1, (1,), ()): ("1", "1"),
  155. (II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
  156. (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),
  157. (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
  158. (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
  159. (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
  160. (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
  161. (II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
  162. (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
  163. (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
  164. (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
  165. (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
  166. (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
  167. (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
  168. (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
  169. (II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
  170. (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
  171. (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
  172. (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
  173. (II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
  174. (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
  175. (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
  176. (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
  177. (II, 1, (1,), 1, (8,), ()): ("L", "L"),
  178. (MM, 1, (1,), 1, (8,), ()): ("L", "L"),
  179. (II, 1, (2,), 1, (8,), ()): ("L", "L"),
  180. (MM, 1, (2,), 1, (8,), ()): ("L", "L"),
  181. (II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
  182. (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),
  183. (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
  184. (II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),
  185. (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
  186. (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
  187. (II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),
  188. (II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),
  189. (MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),
  190. (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
  191. (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
  192. (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
  193. (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
  194. (MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),
  195. (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
  196. (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),
  197. (II, 1, (1,), 1, (8, 8), (0,)): ("L", "LX"),
  198. (MM, 1, (1,), 1, (8, 8), (0,)): ("L", "LX"),
  199. (II, 1, (1,), 1, (8, 8), (1,)): ("La", "La"),
  200. (MM, 1, (1,), 1, (8, 8), (1,)): ("La", "La"),
  201. (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
  202. (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
  203. (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
  204. (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
  205. (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
  206. (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
  207. (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
  208. (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
  209. (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
  210. (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
  211. (II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
  212. (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
  213. (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
  214. (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
  215. (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
  216. (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
  217. (II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
  218. (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
  219. (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
  220. (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
  221. (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
  222. (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
  223. (II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
  224. (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
  225. (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
  226. (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
  227. (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
  228. (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
  229. (II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),
  230. (MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),
  231. (II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),
  232. (MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),
  233. (II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),
  234. (MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),
  235. (II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),
  236. (MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),
  237. (II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),
  238. (MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),
  239. (II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
  240. (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
  241. (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
  242. (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
  243. (II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
  244. (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
  245. (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
  246. (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
  247. (II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
  248. (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
  249. (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
  250. (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
  251. (II, 3, (1,), 1, (8,), ()): ("P", "P"),
  252. (MM, 3, (1,), 1, (8,), ()): ("P", "P"),
  253. (II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
  254. (MM, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
  255. (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
  256. (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
  257. (II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
  258. (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),
  259. (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
  260. (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
  261. (II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
  262. (MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
  263. (II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
  264. (MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
  265. (II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),
  266. (MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"),
  267. (II, 6, (1,), 1, (8,), ()): ("L", "L"),
  268. (MM, 6, (1,), 1, (8,), ()): ("L", "L"),
  269. (II, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),
  270. (MM, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),
  271. (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
  272. (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
  273. }
  274. MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)
  275. PREFIXES = [
  276. b"MM\x00\x2a", # Valid TIFF header with big-endian byte order
  277. b"II\x2a\x00", # Valid TIFF header with little-endian byte order
  278. b"MM\x2a\x00", # Invalid TIFF header, assume big-endian
  279. b"II\x00\x2a", # Invalid TIFF header, assume little-endian
  280. b"MM\x00\x2b", # BigTIFF with big-endian byte order
  281. b"II\x2b\x00", # BigTIFF with little-endian byte order
  282. ]
  283. def _accept(prefix: bytes) -> bool:
  284. return prefix.startswith(tuple(PREFIXES))
  285. def _limit_rational(
  286. val: float | Fraction | IFDRational, max_val: int
  287. ) -> tuple[IntegralLike, IntegralLike]:
  288. inv = abs(val) > 1
  289. n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
  290. return n_d[::-1] if inv else n_d
  291. def _limit_signed_rational(
  292. val: IFDRational, max_val: int, min_val: int
  293. ) -> tuple[IntegralLike, IntegralLike]:
  294. frac = Fraction(val)
  295. n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator
  296. if min(float(i) for i in n_d) < min_val:
  297. n_d = _limit_rational(val, abs(min_val))
  298. n_d_float = tuple(float(i) for i in n_d)
  299. if max(n_d_float) > max_val:
  300. n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val)
  301. return n_d
  302. ##
  303. # Wrapper for TIFF IFDs.
  304. _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {}
  305. _write_dispatch: dict[int, Callable[..., Any]] = {}
  306. def _delegate(op: str) -> Any:
  307. def delegate(
  308. self: IFDRational, *args: tuple[float, ...]
  309. ) -> bool | float | Fraction:
  310. return getattr(self._val, op)(*args)
  311. return delegate
  312. class IFDRational(Rational):
  313. """Implements a rational class where 0/0 is a legal value to match
  314. the in the wild use of exif rationals.
  315. e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
  316. """
  317. """ If the denominator is 0, store this as a float('nan'), otherwise store
  318. as a fractions.Fraction(). Delegate as appropriate
  319. """
  320. __slots__ = ("_numerator", "_denominator", "_val")
  321. def __init__(
  322. self, value: float | Fraction | IFDRational, denominator: int = 1
  323. ) -> None:
  324. """
  325. :param value: either an integer numerator, a
  326. float/rational/other number, or an IFDRational
  327. :param denominator: Optional integer denominator
  328. """
  329. self._val: Fraction | float
  330. if isinstance(value, IFDRational):
  331. self._numerator = value.numerator
  332. self._denominator = value.denominator
  333. self._val = value._val
  334. return
  335. if isinstance(value, Fraction):
  336. self._numerator = value.numerator
  337. self._denominator = value.denominator
  338. else:
  339. if TYPE_CHECKING:
  340. self._numerator = cast("IntegralLike", value)
  341. else:
  342. self._numerator = value
  343. self._denominator = denominator
  344. if denominator == 0:
  345. self._val = float("nan")
  346. elif denominator == 1:
  347. self._val = Fraction(value)
  348. elif int(value) == value:
  349. self._val = Fraction(int(value), denominator)
  350. else:
  351. self._val = Fraction(value / denominator)
  352. @property
  353. def numerator(self) -> IntegralLike:
  354. return self._numerator
  355. @property
  356. def denominator(self) -> int:
  357. return self._denominator
  358. def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]:
  359. """
  360. :param max_denominator: Integer, the maximum denominator value
  361. :returns: Tuple of (numerator, denominator)
  362. """
  363. if self.denominator == 0:
  364. return self.numerator, self.denominator
  365. assert isinstance(self._val, Fraction)
  366. f = self._val.limit_denominator(max_denominator)
  367. return f.numerator, f.denominator
  368. def __repr__(self) -> str:
  369. return str(float(self._val))
  370. def __hash__(self) -> int: # type: ignore[override]
  371. return self._val.__hash__()
  372. def __eq__(self, other: object) -> bool:
  373. val = self._val
  374. if isinstance(other, IFDRational):
  375. other = other._val
  376. if isinstance(other, float):
  377. val = float(val)
  378. return val == other
  379. def __getstate__(self) -> list[float | Fraction | IntegralLike]:
  380. return [self._val, self._numerator, self._denominator]
  381. def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None:
  382. IFDRational.__init__(self, 0)
  383. _val, _numerator, _denominator = state
  384. assert isinstance(_val, (float, Fraction))
  385. self._val = _val
  386. if TYPE_CHECKING:
  387. self._numerator = cast("IntegralLike", _numerator)
  388. else:
  389. self._numerator = _numerator
  390. assert isinstance(_denominator, int)
  391. self._denominator = _denominator
  392. """ a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul',
  393. 'truediv', 'rtruediv', 'floordiv', 'rfloordiv',
  394. 'mod','rmod', 'pow','rpow', 'pos', 'neg',
  395. 'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool',
  396. 'ceil', 'floor', 'round']
  397. print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
  398. """
  399. __add__ = _delegate("__add__")
  400. __radd__ = _delegate("__radd__")
  401. __sub__ = _delegate("__sub__")
  402. __rsub__ = _delegate("__rsub__")
  403. __mul__ = _delegate("__mul__")
  404. __rmul__ = _delegate("__rmul__")
  405. __truediv__ = _delegate("__truediv__")
  406. __rtruediv__ = _delegate("__rtruediv__")
  407. __floordiv__ = _delegate("__floordiv__")
  408. __rfloordiv__ = _delegate("__rfloordiv__")
  409. __mod__ = _delegate("__mod__")
  410. __rmod__ = _delegate("__rmod__")
  411. __pow__ = _delegate("__pow__")
  412. __rpow__ = _delegate("__rpow__")
  413. __pos__ = _delegate("__pos__")
  414. __neg__ = _delegate("__neg__")
  415. __abs__ = _delegate("__abs__")
  416. __trunc__ = _delegate("__trunc__")
  417. __lt__ = _delegate("__lt__")
  418. __gt__ = _delegate("__gt__")
  419. __le__ = _delegate("__le__")
  420. __ge__ = _delegate("__ge__")
  421. __bool__ = _delegate("__bool__")
  422. __ceil__ = _delegate("__ceil__")
  423. __floor__ = _delegate("__floor__")
  424. __round__ = _delegate("__round__")
  425. __float__ = _delegate("__float__")
  426. __int__ = _delegate("__int__")
  427. _LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any]
  428. def _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]:
  429. def decorator(func: _LoaderFunc) -> _LoaderFunc:
  430. from .TiffTags import TYPES
  431. if func.__name__.startswith("load_"):
  432. TYPES[idx] = func.__name__[5:].replace("_", " ")
  433. _load_dispatch[idx] = size, func # noqa: F821
  434. return func
  435. return decorator
  436. def _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
  437. def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
  438. _write_dispatch[idx] = func # noqa: F821
  439. return func
  440. return decorator
  441. def _register_basic(idx_fmt_name: tuple[int, str, str]) -> None:
  442. from .TiffTags import TYPES
  443. idx, fmt, name = idx_fmt_name
  444. TYPES[idx] = name
  445. size = struct.calcsize(f"={fmt}")
  446. def basic_handler(
  447. self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True
  448. ) -> tuple[Any, ...]:
  449. return self._unpack(f"{len(data) // size}{fmt}", data)
  450. _load_dispatch[idx] = size, basic_handler # noqa: F821
  451. _write_dispatch[idx] = lambda self, *values: ( # noqa: F821
  452. b"".join(self._pack(fmt, value) for value in values)
  453. )
  454. if TYPE_CHECKING:
  455. _IFDv2Base = MutableMapping[int, Any]
  456. else:
  457. _IFDv2Base = MutableMapping
  458. class ImageFileDirectory_v2(_IFDv2Base):
  459. """This class represents a TIFF tag directory. To speed things up, we
  460. don't decode tags unless they're asked for.
  461. Exposes a dictionary interface of the tags in the directory::
  462. ifd = ImageFileDirectory_v2()
  463. ifd[key] = 'Some Data'
  464. ifd.tagtype[key] = TiffTags.ASCII
  465. print(ifd[key])
  466. 'Some Data'
  467. Individual values are returned as the strings or numbers, sequences are
  468. returned as tuples of the values.
  469. The tiff metadata type of each item is stored in a dictionary of
  470. tag types in
  471. :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
  472. are read from a tiff file, guessed from the type added, or added
  473. manually.
  474. Data Structures:
  475. * ``self.tagtype = {}``
  476. * Key: numerical TIFF tag number
  477. * Value: integer corresponding to the data type from
  478. :py:data:`.TiffTags.TYPES`
  479. .. versionadded:: 3.0.0
  480. 'Internal' data structures:
  481. * ``self._tags_v2 = {}``
  482. * Key: numerical TIFF tag number
  483. * Value: decoded data, as tuple for multiple values
  484. * ``self._tagdata = {}``
  485. * Key: numerical TIFF tag number
  486. * Value: undecoded byte string from file
  487. * ``self._tags_v1 = {}``
  488. * Key: numerical TIFF tag number
  489. * Value: decoded data in the v1 format
  490. Tags will be found in the private attributes ``self._tagdata``, and in
  491. ``self._tags_v2`` once decoded.
  492. ``self.legacy_api`` is a value for internal use, and shouldn't be changed
  493. from outside code. In cooperation with
  494. :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api``
  495. is true, then decoded tags will be populated into both ``_tags_v1`` and
  496. ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF
  497. save routine. Tags should be read from ``_tags_v1`` if
  498. ``legacy_api == true``.
  499. """
  500. _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {}
  501. _write_dispatch: dict[int, Callable[..., Any]] = {}
  502. def __init__(
  503. self,
  504. ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00",
  505. prefix: bytes | None = None,
  506. group: int | None = None,
  507. ) -> None:
  508. """Initialize an ImageFileDirectory.
  509. To construct an ImageFileDirectory from a real file, pass the 8-byte
  510. magic header to the constructor. To only set the endianness, pass it
  511. as the 'prefix' keyword argument.
  512. :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
  513. endianness.
  514. :param prefix: Override the endianness of the file.
  515. """
  516. if not _accept(ifh):
  517. msg = f"not a TIFF file (header {repr(ifh)} not valid)"
  518. raise SyntaxError(msg)
  519. self._prefix = prefix if prefix is not None else ifh[:2]
  520. if self._prefix == MM:
  521. self._endian = ">"
  522. elif self._prefix == II:
  523. self._endian = "<"
  524. else:
  525. msg = "not a TIFF IFD"
  526. raise SyntaxError(msg)
  527. self._bigtiff = ifh[2] == 43
  528. self.group = group
  529. self.tagtype: dict[int, int] = {}
  530. """ Dictionary of tag types """
  531. self.reset()
  532. # Maximum total out-of-line tag data that load() may read, as well
  533. # as the size of the stream. Set by TiffImageFile so that
  534. # all frames of a file share one budget.
  535. self._tag_data_limit: int | None = None
  536. self.next = (
  537. self._unpack("Q", ifh[8:])[0]
  538. if self._bigtiff
  539. else self._unpack("L", ifh[4:])[0]
  540. )
  541. self._legacy_api = False
  542. prefix = property(lambda self: self._prefix)
  543. offset = property(lambda self: self._offset)
  544. @property
  545. def legacy_api(self) -> bool:
  546. return self._legacy_api
  547. @legacy_api.setter
  548. def legacy_api(self, value: bool) -> NoReturn:
  549. msg = "Not allowing setting of legacy api"
  550. raise Exception(msg)
  551. def reset(self) -> None:
  552. self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false
  553. self._tags_v2: dict[int, Any] = {} # main tag storage
  554. self._tagdata: dict[int, bytes] = {}
  555. self.tagtype = {} # added 2008-06-05 by Florian Hoech
  556. self._next = None
  557. self._offset: int | None = None
  558. def __str__(self) -> str:
  559. return str(dict(self))
  560. def named(self) -> dict[str, Any]:
  561. """
  562. :returns: dict of name|key: value
  563. Returns the complete tag dictionary, with named tags where possible.
  564. """
  565. return {
  566. TiffTags.lookup(code, self.group).name: value
  567. for code, value in self.items()
  568. }
  569. def __len__(self) -> int:
  570. return len(set(self._tagdata) | set(self._tags_v2))
  571. def __getitem__(self, tag: int) -> Any:
  572. if tag not in self._tags_v2: # unpack on the fly
  573. data = self._tagdata[tag]
  574. typ = self.tagtype[tag]
  575. size, handler = self._load_dispatch[typ]
  576. self[tag] = handler(self, data, self.legacy_api) # check type
  577. val = self._tags_v2[tag]
  578. if self.legacy_api and not isinstance(val, (tuple, bytes)):
  579. val = (val,)
  580. return val
  581. def __contains__(self, tag: object) -> bool:
  582. return tag in self._tags_v2 or tag in self._tagdata
  583. def __setitem__(self, tag: int, value: Any) -> None:
  584. self._setitem(tag, value, self.legacy_api)
  585. def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None:
  586. basetypes = (Number, bytes, str)
  587. info = TiffTags.lookup(tag, self.group)
  588. values = [value] if isinstance(value, basetypes) else value
  589. if tag not in self.tagtype:
  590. if info.type:
  591. self.tagtype[tag] = info.type
  592. else:
  593. self.tagtype[tag] = TiffTags.UNDEFINED
  594. if all(isinstance(v, IFDRational) for v in values):
  595. for v in values:
  596. if v < IFDRational(0):
  597. self.tagtype[tag] = TiffTags.SIGNED_RATIONAL
  598. break
  599. else:
  600. self.tagtype[tag] = TiffTags.RATIONAL
  601. elif all(isinstance(v, int) for v in values):
  602. short = True
  603. signed_short = True
  604. long = True
  605. for v in values:
  606. assert isinstance(v, int)
  607. if short and not (0 <= v < 2**16):
  608. short = False
  609. if signed_short and not (-(2**15) < v < 2**15):
  610. signed_short = False
  611. if long and v < 0:
  612. long = False
  613. if short:
  614. self.tagtype[tag] = TiffTags.SHORT
  615. elif signed_short:
  616. self.tagtype[tag] = TiffTags.SIGNED_SHORT
  617. elif long:
  618. self.tagtype[tag] = TiffTags.LONG
  619. else:
  620. self.tagtype[tag] = TiffTags.SIGNED_LONG
  621. elif all(isinstance(v, float) for v in values):
  622. self.tagtype[tag] = TiffTags.DOUBLE
  623. elif all(isinstance(v, str) for v in values):
  624. self.tagtype[tag] = TiffTags.ASCII
  625. elif all(isinstance(v, bytes) for v in values):
  626. self.tagtype[tag] = TiffTags.BYTE
  627. if self.tagtype[tag] == TiffTags.UNDEFINED:
  628. values = [
  629. v.encode("ascii", "replace") if isinstance(v, str) else v
  630. for v in values
  631. ]
  632. elif self.tagtype[tag] == TiffTags.RATIONAL:
  633. values = [float(v) if isinstance(v, int) else v for v in values]
  634. is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict)
  635. if not is_ifd:
  636. values = tuple(
  637. info.cvt_enum(value) if isinstance(value, str) else value
  638. for value in values
  639. )
  640. dest = self._tags_v1 if legacy_api else self._tags_v2
  641. # Three branches:
  642. # Spec'd length == 1, Actual length 1, store as element
  643. # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed.
  644. # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple.
  645. # Don't mess with the legacy api, since it's frozen.
  646. if not is_ifd and (
  647. (info.length == 1)
  648. or self.tagtype[tag] == TiffTags.BYTE
  649. or (info.length is None and len(values) == 1 and not legacy_api)
  650. ):
  651. # Don't mess with the legacy api, since it's frozen.
  652. if legacy_api and self.tagtype[tag] in [
  653. TiffTags.RATIONAL,
  654. TiffTags.SIGNED_RATIONAL,
  655. ]: # rationals
  656. values = (values,)
  657. try:
  658. (dest[tag],) = values
  659. except ValueError:
  660. # We've got a builtin tag with 1 expected entry
  661. if tag != PHOTOMETRIC_INTERPRETATION:
  662. warnings.warn(
  663. f"Metadata Warning, tag {tag} had too many entries: "
  664. f"{len(values)}, expected 1"
  665. )
  666. dest[tag] = values[0]
  667. else:
  668. # Spec'd length > 1 or undefined
  669. # Unspec'd, and length > 1
  670. dest[tag] = values
  671. def __delitem__(self, tag: int) -> None:
  672. self._tags_v2.pop(tag, None)
  673. self._tags_v1.pop(tag, None)
  674. self._tagdata.pop(tag, None)
  675. def __iter__(self) -> Iterator[int]:
  676. return iter(set(self._tagdata) | set(self._tags_v2))
  677. def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]:
  678. return struct.unpack(self._endian + fmt, data)
  679. def _pack(self, fmt: str, *values: Any) -> bytes:
  680. return struct.pack(self._endian + fmt, *values)
  681. list(
  682. map(
  683. _register_basic,
  684. [
  685. (TiffTags.SHORT, "H", "short"),
  686. (TiffTags.LONG, "L", "long"),
  687. (TiffTags.SIGNED_BYTE, "b", "signed byte"),
  688. (TiffTags.SIGNED_SHORT, "h", "signed short"),
  689. (TiffTags.SIGNED_LONG, "l", "signed long"),
  690. (TiffTags.FLOAT, "f", "float"),
  691. (TiffTags.DOUBLE, "d", "double"),
  692. (TiffTags.IFD, "L", "long"),
  693. (TiffTags.LONG8, "Q", "long8"),
  694. ],
  695. )
  696. )
  697. @_register_loader(1, 1) # Basic type, except for the legacy API.
  698. def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes:
  699. return data
  700. @_register_writer(1) # Basic type, except for the legacy API.
  701. def write_byte(self, data: bytes | int | IFDRational) -> bytes:
  702. if isinstance(data, IFDRational):
  703. data = int(data)
  704. if isinstance(data, int):
  705. data = bytes((data,))
  706. return data
  707. @_register_loader(2, 1)
  708. def load_string(self, data: bytes, legacy_api: bool = True) -> str:
  709. if data.endswith(b"\0"):
  710. data = data[:-1]
  711. return data.decode("latin-1", "replace")
  712. @_register_writer(2)
  713. def write_string(self, value: str | bytes | int) -> bytes:
  714. # remerge of https://github.com/python-pillow/Pillow/pull/1416
  715. if isinstance(value, int):
  716. value = str(value)
  717. if not isinstance(value, bytes):
  718. value = value.encode("ascii", "replace")
  719. return value + b"\0"
  720. @_register_loader(5, 8)
  721. def load_rational(
  722. self, data: bytes, legacy_api: bool = True
  723. ) -> tuple[tuple[int, int] | IFDRational, ...]:
  724. vals = self._unpack(f"{len(data) // 4}L", data)
  725. def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
  726. return (a, b) if legacy_api else IFDRational(a, b)
  727. return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
  728. @_register_writer(5)
  729. def write_rational(self, *values: IFDRational) -> bytes:
  730. return b"".join(
  731. self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values
  732. )
  733. @_register_loader(7, 1)
  734. def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes:
  735. return data
  736. @_register_writer(7)
  737. def write_undefined(self, value: bytes | int | IFDRational) -> bytes:
  738. if isinstance(value, IFDRational):
  739. value = int(value)
  740. if isinstance(value, int):
  741. value = str(value).encode("ascii", "replace")
  742. return value
  743. @_register_loader(10, 8)
  744. def load_signed_rational(
  745. self, data: bytes, legacy_api: bool = True
  746. ) -> tuple[tuple[int, int] | IFDRational, ...]:
  747. vals = self._unpack(f"{len(data) // 4}l", data)
  748. def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
  749. return (a, b) if legacy_api else IFDRational(a, b)
  750. return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
  751. @_register_writer(10)
  752. def write_signed_rational(self, *values: IFDRational) -> bytes:
  753. return b"".join(
  754. self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31)))
  755. for frac in values
  756. )
  757. def _ensure_read(self, fp: IO[bytes], size: int) -> bytes:
  758. ret = fp.read(size)
  759. if len(ret) != size:
  760. msg = (
  761. "Corrupt EXIF data. "
  762. f"Expecting to read {size} bytes but only got {len(ret)}. "
  763. )
  764. raise OSError(msg)
  765. return ret
  766. def load(self, fp: IO[bytes]) -> None:
  767. self.reset()
  768. self._offset = fp.tell()
  769. fp.seek(0, io.SEEK_END)
  770. limit = fp.tell()
  771. fp.seek(self._offset)
  772. if self._tag_data_limit is not None:
  773. limit = min(limit, self._tag_data_limit)
  774. self._tag_data_size = 0
  775. try:
  776. tag_count = (
  777. self._unpack("Q", self._ensure_read(fp, 8))
  778. if self._bigtiff
  779. else self._unpack("H", self._ensure_read(fp, 2))
  780. )[0]
  781. total_size = 0
  782. for i in range(tag_count):
  783. tag, typ, count, data = (
  784. self._unpack("HHQ8s", self._ensure_read(fp, 20))
  785. if self._bigtiff
  786. else self._unpack("HHL4s", self._ensure_read(fp, 12))
  787. )
  788. if tag in self._tagdata:
  789. continue
  790. tagname = TiffTags.lookup(tag, self.group).name
  791. typname = TYPES.get(typ, "unknown")
  792. msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})"
  793. try:
  794. unit_size, handler = self._load_dispatch[typ]
  795. except KeyError:
  796. logger.debug("%s - unsupported type %s", msg, typ)
  797. continue # ignore unsupported type
  798. size = count * unit_size
  799. if size > (8 if self._bigtiff else 4):
  800. here = fp.tell()
  801. (offset,) = self._unpack("Q" if self._bigtiff else "L", data)
  802. msg += f" Tag Location: {here} - Data Location: {offset}"
  803. if offset >= 2**63:
  804. warnings.warn("Tag offset too large")
  805. continue
  806. # Well-formed IFD values should fit within the stream they
  807. # are read from, even before accounting for overlaps.
  808. total_size += size
  809. if total_size > limit:
  810. warnings.warn(f"Tag data larger than file. Skipping tag {tag}")
  811. continue
  812. self._tag_data_size += size
  813. fp.seek(offset)
  814. data = ImageFile._safe_read(fp, size)
  815. fp.seek(here)
  816. else:
  817. data = data[:size]
  818. if len(data) != size:
  819. warnings.warn(
  820. "Possibly corrupt EXIF data. "
  821. f"Expecting to read {size} bytes but only got {len(data)}."
  822. f" Skipping tag {tag}"
  823. )
  824. logger.debug(msg)
  825. continue
  826. if not data:
  827. logger.debug(msg)
  828. continue
  829. self._tagdata[tag] = data
  830. self.tagtype[tag] = typ
  831. msg += " - value: "
  832. msg += f"<table: {size} bytes>" if size > 32 else repr(data)
  833. logger.debug(msg)
  834. (self.next,) = (
  835. self._unpack("Q", self._ensure_read(fp, 8))
  836. if self._bigtiff
  837. else self._unpack("L", self._ensure_read(fp, 4))
  838. )
  839. except OSError as msg:
  840. warnings.warn(str(msg))
  841. return
  842. def _get_ifh(self) -> bytes:
  843. ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42)
  844. if self._bigtiff:
  845. ifh += self._pack("HH", 8, 0)
  846. ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8)
  847. return ifh
  848. def tobytes(self, offset: int = 0) -> bytes:
  849. # FIXME What about tagdata?
  850. result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2))
  851. entries: list[tuple[int, int, int, bytes, bytes]] = []
  852. fmt = "Q" if self._bigtiff else "L"
  853. fmt_size = 8 if self._bigtiff else 4
  854. offset += (
  855. len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size
  856. )
  857. stripoffsets = None
  858. # pass 1: convert tags to binary format
  859. # always write tags in ascending order
  860. for tag, value in sorted(self._tags_v2.items()):
  861. if tag == STRIPOFFSETS:
  862. stripoffsets = len(entries)
  863. typ = self.tagtype[tag]
  864. logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))
  865. is_ifd = typ == TiffTags.LONG and isinstance(value, dict)
  866. if is_ifd:
  867. ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag)
  868. values = self._tags_v2[tag]
  869. for ifd_tag, ifd_value in values.items():
  870. ifd[ifd_tag] = ifd_value
  871. data = ifd.tobytes(offset)
  872. else:
  873. values = value if isinstance(value, tuple) else (value,)
  874. data = self._write_dispatch[typ](self, *values)
  875. tagname = TiffTags.lookup(tag, self.group).name
  876. typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")
  877. msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: "
  878. msg += f"<table: {len(data)} bytes>" if len(data) >= 16 else str(values)
  879. logger.debug(msg)
  880. # count is sum of lengths for string and arbitrary data
  881. if is_ifd:
  882. count = 1
  883. elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
  884. count = len(data)
  885. else:
  886. count = len(values)
  887. # figure out if data fits into the entry
  888. if len(data) <= fmt_size:
  889. entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b""))
  890. else:
  891. entries.append((tag, typ, count, self._pack(fmt, offset), data))
  892. offset += (len(data) + 1) // 2 * 2 # pad to word
  893. # update strip offset data to point beyond auxiliary data
  894. if stripoffsets is not None:
  895. tag, typ, count, value, data = entries[stripoffsets]
  896. if data:
  897. size, handler = self._load_dispatch[typ]
  898. values = [val + offset for val in handler(self, data, self.legacy_api)]
  899. data = self._write_dispatch[typ](self, *values)
  900. else:
  901. value = self._pack(fmt, self._unpack(fmt, value)[0] + offset)
  902. entries[stripoffsets] = tag, typ, count, value, data
  903. # pass 2: write entries to file
  904. for tag, typ, count, value, data in entries:
  905. logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))
  906. result += self._pack(
  907. "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value
  908. )
  909. # -- overwrite here for multi-page --
  910. result += self._pack(fmt, 0) # end of entries
  911. # pass 3: write auxiliary data to file
  912. for tag, typ, count, value, data in entries:
  913. result += data
  914. if len(data) & 1:
  915. result += b"\0"
  916. return result
  917. def save(self, fp: IO[bytes]) -> int:
  918. if fp.tell() == 0: # skip TIFF header on subsequent pages
  919. fp.write(self._get_ifh())
  920. offset = fp.tell()
  921. result = self.tobytes(offset)
  922. fp.write(result)
  923. return offset + len(result)
  924. ImageFileDirectory_v2._load_dispatch = _load_dispatch
  925. ImageFileDirectory_v2._write_dispatch = _write_dispatch
  926. for idx, name in TYPES.items():
  927. name = name.replace(" ", "_")
  928. setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])
  929. setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])
  930. del _load_dispatch, _write_dispatch, idx, name
  931. # Legacy ImageFileDirectory support.
  932. class ImageFileDirectory_v1(ImageFileDirectory_v2):
  933. """This class represents the **legacy** interface to a TIFF tag directory.
  934. Exposes a dictionary interface of the tags in the directory::
  935. ifd = ImageFileDirectory_v1()
  936. ifd[key] = 'Some Data'
  937. ifd.tagtype[key] = TiffTags.ASCII
  938. print(ifd[key])
  939. ('Some Data',)
  940. Also contains a dictionary of tag types as read from the tiff image file,
  941. :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.
  942. Values are returned as a tuple.
  943. .. deprecated:: 3.0.0
  944. """
  945. def __init__(self, *args: Any, **kwargs: Any) -> None:
  946. super().__init__(*args, **kwargs)
  947. self._legacy_api = True
  948. tags = property(lambda self: self._tags_v1)
  949. tagdata = property(lambda self: self._tagdata)
  950. # defined in ImageFileDirectory_v2
  951. tagtype: dict[int, int]
  952. """Dictionary of tag types"""
  953. @classmethod
  954. def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1:
  955. """Returns an
  956. :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
  957. instance with the same data as is contained in the original
  958. :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
  959. instance.
  960. :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
  961. """
  962. ifd = cls(prefix=original.prefix)
  963. ifd._tagdata = original._tagdata
  964. ifd.tagtype = original.tagtype
  965. ifd.next = original.next # an indicator for multipage tiffs
  966. return ifd
  967. def to_v2(self) -> ImageFileDirectory_v2:
  968. """Returns an
  969. :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
  970. instance with the same data as is contained in the original
  971. :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
  972. instance.
  973. :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
  974. """
  975. ifd = ImageFileDirectory_v2(prefix=self.prefix)
  976. ifd._tagdata = dict(self._tagdata)
  977. ifd.tagtype = dict(self.tagtype)
  978. ifd._tags_v2 = dict(self._tags_v2)
  979. return ifd
  980. def __contains__(self, tag: object) -> bool:
  981. return tag in self._tags_v1 or tag in self._tagdata
  982. def __len__(self) -> int:
  983. return len(set(self._tagdata) | set(self._tags_v1))
  984. def __iter__(self) -> Iterator[int]:
  985. return iter(set(self._tagdata) | set(self._tags_v1))
  986. def __setitem__(self, tag: int, value: Any) -> None:
  987. for legacy_api in (False, True):
  988. self._setitem(tag, value, legacy_api)
  989. def __getitem__(self, tag: int) -> Any:
  990. if tag not in self._tags_v1: # unpack on the fly
  991. data = self._tagdata[tag]
  992. typ = self.tagtype[tag]
  993. size, handler = self._load_dispatch[typ]
  994. for legacy in (False, True):
  995. self._setitem(tag, handler(self, data, legacy), legacy)
  996. val = self._tags_v1[tag]
  997. if not isinstance(val, (tuple, bytes)):
  998. val = (val,)
  999. return val
  1000. # undone -- switch this pointer
  1001. ImageFileDirectory = ImageFileDirectory_v1
  1002. ##
  1003. # Image plugin for TIFF files.
  1004. class TiffImageFile(ImageFile.ImageFile):
  1005. format = "TIFF"
  1006. format_description = "Adobe TIFF"
  1007. _close_exclusive_fp_after_loading = False
  1008. def __init__(
  1009. self,
  1010. fp: StrOrBytesPath | IO[bytes],
  1011. filename: str | bytes | None = None,
  1012. ) -> None:
  1013. self.tag_v2: ImageFileDirectory_v2
  1014. """ Image file directory (tag dictionary) """
  1015. self.tag: ImageFileDirectory_v1
  1016. """ Legacy tag entries """
  1017. self._n_frames: int | None = None
  1018. super().__init__(fp, filename)
  1019. def _open(self) -> None:
  1020. """Open the first image in a TIFF file"""
  1021. # Header
  1022. assert self.fp is not None
  1023. ifh = self.fp.read(8)
  1024. if ifh[2] == 43:
  1025. ifh += self.fp.read(8)
  1026. self.tag_v2 = ImageFileDirectory_v2(ifh)
  1027. # setup frame pointers
  1028. self.__first = self.__next = self.tag_v2.next
  1029. self.__frame = -1
  1030. self._fp = self.fp
  1031. self._frame_pos: list[int] = []
  1032. # Out-of-line tag data is budgeted across all frames, so that many
  1033. # frames cannot each read the same data. Each frame's limit is fixed
  1034. # when it is first loaded, so that reloading it gives the same tags.
  1035. self.fp.seek(0, io.SEEK_END)
  1036. self._tag_data_remaining = self.fp.tell()
  1037. self._tag_data_limits: list[int] = []
  1038. logger.debug("*** TiffImageFile._open ***")
  1039. logger.debug("- __first: %s", self.__first)
  1040. logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)
  1041. # and load the first frame
  1042. self._seek(0)
  1043. @property
  1044. def n_frames(self) -> int:
  1045. current_n_frames = self._n_frames
  1046. if current_n_frames is None:
  1047. current = self.tell()
  1048. self._seek(len(self._frame_pos))
  1049. while self._n_frames is None:
  1050. self._seek(self.tell() + 1)
  1051. self.seek(current)
  1052. assert self._n_frames is not None
  1053. return self._n_frames
  1054. def seek(self, frame: int) -> None:
  1055. """Select a given frame as current image"""
  1056. if not self._seek_check(frame):
  1057. return
  1058. self._seek(frame)
  1059. if self._im is not None and (
  1060. self.im.size != self._tile_size
  1061. or self.im.mode != self.mode
  1062. or self.readonly
  1063. ):
  1064. self._im = None
  1065. def _seek(self, frame: int) -> None:
  1066. if isinstance(self._fp, DeferredError):
  1067. raise self._fp.ex
  1068. self.fp = self._fp
  1069. while len(self._frame_pos) <= frame:
  1070. if not self.__next:
  1071. msg = "no more images in TIFF file"
  1072. raise EOFError(msg)
  1073. logger.debug(
  1074. "Seeking to frame %s, on frame %s, __next %s, location: %s",
  1075. frame,
  1076. self.__frame,
  1077. self.__next,
  1078. self.fp.tell(),
  1079. )
  1080. if self.__next >= 2**63:
  1081. msg = "Unable to seek to frame"
  1082. raise ValueError(msg)
  1083. self.fp.seek(self.__next)
  1084. self._frame_pos.append(self.__next)
  1085. self._tag_data_limits.append(self._tag_data_remaining)
  1086. logger.debug("Loading tags, location: %s", self.fp.tell())
  1087. self.tag_v2._tag_data_limit = self._tag_data_remaining
  1088. self.tag_v2.load(self.fp)
  1089. self._tag_data_remaining -= self.tag_v2._tag_data_size
  1090. if self.tag_v2.next in self._frame_pos:
  1091. # This IFD has already been processed
  1092. # Declare this to be the end of the image
  1093. self.__next = 0
  1094. else:
  1095. self.__next = self.tag_v2.next
  1096. if self.__next == 0 and self._n_frames is None:
  1097. self._n_frames = frame + 1
  1098. if not hasattr(self, "is_animated"):
  1099. self.is_animated = self.__next != 0
  1100. self.__frame += 1
  1101. self.fp.seek(self._frame_pos[frame])
  1102. self.tag_v2._tag_data_limit = self._tag_data_limits[frame]
  1103. self.tag_v2.load(self.fp)
  1104. if XMP in self.tag_v2:
  1105. xmp = self.tag_v2[XMP]
  1106. if isinstance(xmp, tuple) and len(xmp) == 1:
  1107. xmp = xmp[0]
  1108. self.info["xmp"] = xmp
  1109. elif "xmp" in self.info:
  1110. del self.info["xmp"]
  1111. self._reload_exif()
  1112. # fill the legacy tag/ifd entries
  1113. self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
  1114. self.__frame = frame
  1115. self._setup()
  1116. def tell(self) -> int:
  1117. """Return the current frame number"""
  1118. return self.__frame
  1119. def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]:
  1120. """
  1121. Returns a dictionary of Photoshop "Image Resource Blocks".
  1122. The keys are the image resource ID. For more information, see
  1123. https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727
  1124. :returns: Photoshop "Image Resource Blocks" in a dictionary.
  1125. """
  1126. blocks = {}
  1127. val = self.tag_v2.get(ExifTags.Base.ImageResources)
  1128. if val:
  1129. while val.startswith(b"8BIM") and len(val) >= 12:
  1130. id = i16(val[4:6])
  1131. n = math.ceil((val[6] + 1) / 2) * 2
  1132. try:
  1133. size = i32(val[6 + n : 10 + n])
  1134. except struct.error:
  1135. break
  1136. data = val[10 + n : 10 + n + size]
  1137. blocks[id] = {"data": data}
  1138. val = val[math.ceil((10 + n + size) / 2) * 2 :]
  1139. return blocks
  1140. def load(self) -> Image.core.PixelAccess | None:
  1141. if self.tile and self.use_load_libtiff:
  1142. return self._load_libtiff()
  1143. return super().load()
  1144. def load_prepare(self) -> None:
  1145. if self._im is None:
  1146. Image._decompression_bomb_check(self._tile_size)
  1147. self.im = Image.core.new(self.mode, self._tile_size)
  1148. ImageFile.ImageFile.load_prepare(self)
  1149. def load_end(self) -> None:
  1150. # allow closing if we're on the first frame, there's no next
  1151. # This is the ImageFile.load path only, libtiff specific below.
  1152. if not self.is_animated:
  1153. self._close_exclusive_fp_after_loading = True
  1154. # load IFD data from fp before it is closed
  1155. exif = self.getexif()
  1156. for key in TiffTags.TAGS_V2_GROUPS:
  1157. if key not in exif:
  1158. continue
  1159. exif.get_ifd(key)
  1160. ImageOps.exif_transpose(self, in_place=True)
  1161. if ExifTags.Base.Orientation in self.tag_v2:
  1162. del self.tag_v2[ExifTags.Base.Orientation]
  1163. def _load_libtiff(self) -> Image.core.PixelAccess | None:
  1164. """Overload method triggered when we detect a compressed tiff
  1165. Calls out to libtiff"""
  1166. Image.Image.load(self)
  1167. self.load_prepare()
  1168. if not len(self.tile) == 1:
  1169. msg = "Not exactly one tile"
  1170. raise OSError(msg)
  1171. extents = self.tile[0].extents
  1172. args = self.tile[0].args
  1173. # To be nice on memory footprint, if there's a
  1174. # file descriptor, use that instead of reading
  1175. # into a string in python.
  1176. assert self.fp is not None
  1177. try:
  1178. fp = hasattr(self.fp, "fileno") and self.fp.fileno()
  1179. # flush the file descriptor, prevents error on pypy 2.4+
  1180. # should also eliminate the need for fp.tell
  1181. # in _seek
  1182. if hasattr(self.fp, "flush"):
  1183. self.fp.flush()
  1184. except OSError:
  1185. # io.BytesIO have a fileno, but returns an OSError if
  1186. # it doesn't use a file descriptor.
  1187. fp = False
  1188. if fp:
  1189. assert isinstance(args, tuple)
  1190. args_list = list(args)
  1191. args_list[1] = fp
  1192. args = tuple(args_list)
  1193. decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)
  1194. try:
  1195. decoder.setimage(self.im, extents)
  1196. except ValueError as e:
  1197. msg = "Couldn't set the image"
  1198. raise OSError(msg) from e
  1199. close_self_fp = self._exclusive_fp and not self.is_animated
  1200. if hasattr(self.fp, "getvalue"):
  1201. # We've got a stringio like thing passed in. Yay for all in memory.
  1202. # The decoder needs the entire file in one shot, so there's not
  1203. # a lot we can do here other than give it the entire file.
  1204. # unless we could do something like get the address of the
  1205. # underlying string for stringio.
  1206. #
  1207. # Rearranging for supporting byteio items, since they have a fileno
  1208. # that returns an OSError if there's no underlying fp. Easier to
  1209. # deal with here by reordering.
  1210. logger.debug("have getvalue. just sending in a string from getvalue")
  1211. n, err = decoder.decode(self.fp.getvalue())
  1212. elif fp:
  1213. # we've got a actual file on disk, pass in the fp.
  1214. logger.debug("have fileno, calling fileno version of the decoder.")
  1215. if not close_self_fp:
  1216. self.fp.seek(0)
  1217. # Save and restore the file position, because libtiff will move it
  1218. # outside of the Python runtime, and that will confuse
  1219. # io.BufferedReader and possible others.
  1220. # NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(),
  1221. # because the buffer read head already may not equal the actual
  1222. # file position, and fp.seek() may just adjust it's internal
  1223. # pointer and not actually seek the OS file handle.
  1224. pos = os.lseek(fp, 0, os.SEEK_CUR)
  1225. # 4 bytes, otherwise the trace might error out
  1226. n, err = decoder.decode(b"fpfp")
  1227. os.lseek(fp, pos, os.SEEK_SET)
  1228. else:
  1229. # we have something else.
  1230. logger.debug("don't have fileno or getvalue. just reading")
  1231. self.fp.seek(0)
  1232. # UNDONE -- so much for that buffer size thing.
  1233. n, err = decoder.decode(self.fp.read())
  1234. self.tile = []
  1235. self.readonly = 0
  1236. self.load_end()
  1237. if close_self_fp:
  1238. self.fp.close()
  1239. self.fp = None # might be shared
  1240. if err < 0:
  1241. msg = f"decoder error {err}"
  1242. raise OSError(msg)
  1243. return Image.Image.load(self)
  1244. def _setup(self) -> None:
  1245. """Setup this image object based on current tags"""
  1246. if 0xBC01 in self.tag_v2:
  1247. msg = "Windows Media Photo files not yet supported"
  1248. raise OSError(msg)
  1249. # extract relevant tags
  1250. self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
  1251. self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
  1252. # photometric is a required tag, but not everyone is reading
  1253. # the specification
  1254. photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
  1255. # old style jpeg compression images most certainly are YCbCr
  1256. if self._compression == "tiff_jpeg":
  1257. photo = 6
  1258. fillorder = self.tag_v2.get(FILLORDER, 1)
  1259. logger.debug("*** Summary ***")
  1260. logger.debug("- compression: %s", self._compression)
  1261. logger.debug("- photometric_interpretation: %s", photo)
  1262. logger.debug("- planar_configuration: %s", self._planar_configuration)
  1263. logger.debug("- fill_order: %s", fillorder)
  1264. logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING))
  1265. # size
  1266. try:
  1267. xsize = self.tag_v2[IMAGEWIDTH]
  1268. ysize = self.tag_v2[IMAGELENGTH]
  1269. except KeyError as e:
  1270. msg = "Missing dimensions"
  1271. raise TypeError(msg) from e
  1272. if not isinstance(xsize, int) or not isinstance(ysize, int):
  1273. msg = "Invalid dimensions"
  1274. raise ValueError(msg)
  1275. self._tile_size = xsize, ysize
  1276. orientation = self.tag_v2.get(ExifTags.Base.Orientation)
  1277. if orientation in (5, 6, 7, 8):
  1278. self._size = ysize, xsize
  1279. else:
  1280. self._size = xsize, ysize
  1281. logger.debug("- size: %s", self.size)
  1282. sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))
  1283. if len(sample_format) > 1 and max(sample_format) == min(sample_format):
  1284. # SAMPLEFORMAT is properly per band, so an RGB image will
  1285. # be (1,1,1). But, we don't support per band pixel types,
  1286. # and anything more than one band is a uint8. So, just
  1287. # take the first element. Revisit this if adding support
  1288. # for more exotic images.
  1289. sample_format = (sample_format[0],)
  1290. bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
  1291. extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
  1292. samples_per_pixel = self.tag_v2.get(
  1293. SAMPLESPERPIXEL,
  1294. 3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
  1295. )
  1296. if photo in (2, 6, 8): # RGB, YCbCr, LAB
  1297. bps_count = 3
  1298. elif photo == 5: # CMYK
  1299. bps_count = 4
  1300. else:
  1301. bps_count = 1
  1302. if self._planar_configuration == 2 and extra_tuple and max(extra_tuple) == 0:
  1303. # If components are stored separately,
  1304. # then unspecified extra components at the end can be ignored
  1305. bps_tuple = bps_tuple[: -len(extra_tuple)]
  1306. samples_per_pixel -= len(extra_tuple)
  1307. extra_tuple = ()
  1308. bps_count += len(extra_tuple)
  1309. bps_actual_count = len(bps_tuple)
  1310. if samples_per_pixel > MAX_SAMPLESPERPIXEL:
  1311. # DOS check, samples_per_pixel can be a Long, and we extend the tuple below
  1312. logger.error(
  1313. "More samples per pixel than can be decoded: %s", samples_per_pixel
  1314. )
  1315. msg = "Invalid value for samples per pixel"
  1316. raise SyntaxError(msg)
  1317. if samples_per_pixel < bps_actual_count:
  1318. # If a file has more values in bps_tuple than expected,
  1319. # remove the excess.
  1320. bps_tuple = bps_tuple[:samples_per_pixel]
  1321. elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:
  1322. # If a file has only one value in bps_tuple, when it should have more,
  1323. # presume it is the same number of bits for all of the samples.
  1324. bps_tuple = bps_tuple * samples_per_pixel
  1325. if len(bps_tuple) != samples_per_pixel:
  1326. msg = "unknown data organization"
  1327. raise SyntaxError(msg)
  1328. # mode: check photometric interpretation and bits per pixel
  1329. key = (
  1330. self.tag_v2.prefix,
  1331. photo,
  1332. sample_format,
  1333. fillorder,
  1334. bps_tuple,
  1335. extra_tuple,
  1336. )
  1337. logger.debug("format key: %s", key)
  1338. try:
  1339. self._mode, rawmode = OPEN_INFO[key]
  1340. except KeyError as e:
  1341. logger.debug("- unsupported format")
  1342. msg = "unknown pixel mode"
  1343. raise SyntaxError(msg) from e
  1344. logger.debug("- raw mode: %s", rawmode)
  1345. logger.debug("- pil mode: %s", self.mode)
  1346. self.info["compression"] = self._compression
  1347. xres = self.tag_v2.get(X_RESOLUTION, 1)
  1348. yres = self.tag_v2.get(Y_RESOLUTION, 1)
  1349. if xres and yres:
  1350. resunit = self.tag_v2.get(RESOLUTION_UNIT)
  1351. if resunit == 2: # dots per inch
  1352. self.info["dpi"] = (xres, yres)
  1353. elif resunit == 3: # dots per centimeter. convert to dpi
  1354. self.info["dpi"] = (xres * 2.54, yres * 2.54)
  1355. elif resunit is None: # used to default to 1, but now 2)
  1356. self.info["dpi"] = (xres, yres)
  1357. # For backward compatibility,
  1358. # we also preserve the old behavior
  1359. self.info["resolution"] = xres, yres
  1360. else: # No absolute unit of measurement
  1361. self.info["resolution"] = xres, yres
  1362. # build tile descriptors
  1363. x = y = layer = 0
  1364. self.tile = []
  1365. self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
  1366. if self.use_load_libtiff:
  1367. # Decoder expects entire file as one tile.
  1368. # There's a buffer size limit in load (64k)
  1369. # so large g4 images will fail if we use that
  1370. # function.
  1371. #
  1372. # Setup the one tile for the whole image, then
  1373. # use the _load_libtiff function.
  1374. # libtiff handles the fillmode for us, so 1;IR should
  1375. # actually be 1;I. Including the R double reverses the
  1376. # bits, so stripes of the image are reversed. See
  1377. # https://github.com/python-pillow/Pillow/issues/279
  1378. if fillorder == 2:
  1379. # Replace fillorder with fillorder=1
  1380. key = key[:3] + (1,) + key[4:]
  1381. logger.debug("format key: %s", key)
  1382. # this should always work, since all the
  1383. # fillorder==2 modes have a corresponding
  1384. # fillorder=1 mode
  1385. self._mode, rawmode = OPEN_INFO[key]
  1386. if photo == 6:
  1387. self._mode = "RGB"
  1388. if self._compression in "jpeg" and self._planar_configuration == 1:
  1389. # YCbCr images with new jpeg compression with pixels in one plane
  1390. # unpacked straight into RGB values
  1391. rawmode = "RGB"
  1392. else:
  1393. rawmode = "RGBX"
  1394. # libtiff always returns the bytes in native order.
  1395. # we're expecting image byte order. So, if the rawmode
  1396. # contains I;16, we need to convert from native to image
  1397. # byte order.
  1398. elif rawmode == "I;16":
  1399. rawmode = "I;16N"
  1400. elif rawmode.endswith((";16B", ";16L")):
  1401. rawmode = rawmode[:-1] + "N"
  1402. # Offset in the tile tuple is 0, we go from 0,0 to
  1403. # w,h, and we only do this once -- eds
  1404. a = (rawmode, False, self.tag_v2.offset)
  1405. self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))
  1406. elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
  1407. # striped image
  1408. if STRIPOFFSETS in self.tag_v2:
  1409. offsets = self.tag_v2[STRIPOFFSETS]
  1410. h = self.tag_v2.get(ROWSPERSTRIP, ysize)
  1411. w = xsize
  1412. else:
  1413. # tiled image
  1414. offsets = self.tag_v2[TILEOFFSETS]
  1415. tilewidth = self.tag_v2.get(TILEWIDTH)
  1416. h = self.tag_v2.get(TILELENGTH)
  1417. if not isinstance(tilewidth, int) or not isinstance(h, int):
  1418. msg = "Invalid tile dimensions"
  1419. raise ValueError(msg)
  1420. w = tilewidth
  1421. if w == xsize and h == ysize and self._planar_configuration != 2:
  1422. # Every tile covers the image. Only use the last offset
  1423. offsets = offsets[-1:]
  1424. for offset in offsets:
  1425. if x + w > xsize:
  1426. stride = w * sum(bps_tuple) / 8 # bytes per line
  1427. else:
  1428. stride = 0
  1429. tile_rawmode = rawmode
  1430. if self._planar_configuration == 2:
  1431. # each band on it's own layer
  1432. tile_rawmode = rawmode[layer]
  1433. # adjust stride width accordingly
  1434. stride /= bps_count
  1435. args = (tile_rawmode, int(stride), 1)
  1436. self.tile.append(
  1437. ImageFile._Tile(
  1438. self._compression,
  1439. (x, y, min(x + w, xsize), min(y + h, ysize)),
  1440. offset,
  1441. args,
  1442. )
  1443. )
  1444. x += w
  1445. if x >= xsize:
  1446. x, y = 0, y + h
  1447. if y >= ysize:
  1448. y = 0
  1449. layer += 1
  1450. else:
  1451. logger.debug("- unsupported data organization")
  1452. msg = "unknown data organization"
  1453. raise SyntaxError(msg)
  1454. # Fix up info.
  1455. if ICCPROFILE in self.tag_v2:
  1456. self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
  1457. # fixup palette descriptor
  1458. if self.mode in ["P", "PA"]:
  1459. palette = tuple(b // 256 for b in self.tag_v2[COLORMAP])
  1460. self.palette = ImagePalette.raw("RGB;L", palette)
  1461. else:
  1462. self.palette = None
  1463. #
  1464. # --------------------------------------------------------------------
  1465. # Write TIFF files
  1466. # little endian is default except for image modes with
  1467. # explicit big endian byte-order
  1468. SAVE_INFO = {
  1469. # mode => rawmode, byteorder, photometrics,
  1470. # sampleformat, bitspersample, extra
  1471. "1": ("1", II, 1, 1, (1,), None),
  1472. "L": ("L", II, 1, 1, (8,), None),
  1473. "LA": ("LA", II, 1, 1, (8, 8), 2),
  1474. "P": ("P", II, 3, 1, (8,), None),
  1475. "PA": ("PA", II, 3, 1, (8, 8), 2),
  1476. "I": ("I;32S", II, 1, 2, (32,), None),
  1477. "I;16": ("I;16", II, 1, 1, (16,), None),
  1478. "I;16L": ("I;16L", II, 1, 1, (16,), None),
  1479. "F": ("F;32F", II, 1, 3, (32,), None),
  1480. "RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
  1481. "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
  1482. "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
  1483. "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
  1484. "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
  1485. "LAB": ("LAB", II, 8, 1, (8, 8, 8), None),
  1486. "I;16B": ("I;16B", MM, 1, 1, (16,), None),
  1487. }
  1488. def _validate_tags(tags: dict[int, Any]) -> None:
  1489. if COLORMAP in tags:
  1490. bps = tags.get(BITSPERSAMPLE, 1)
  1491. if isinstance(bps, tuple):
  1492. bps = bps[0]
  1493. expected = (1 << bps) * 3
  1494. if len(tags[COLORMAP]) != expected:
  1495. msg = f"Requiring {expected} items for Colormap"
  1496. raise ValueError(msg)
  1497. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  1498. try:
  1499. rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
  1500. except KeyError as e:
  1501. msg = f"cannot write mode {im.mode} as TIFF"
  1502. raise OSError(msg) from e
  1503. encoderinfo = im.encoderinfo
  1504. encoderconfig = im.encoderconfig
  1505. ifd = ImageFileDirectory_v2(prefix=prefix)
  1506. if encoderinfo.get("big_tiff"):
  1507. ifd._bigtiff = True
  1508. try:
  1509. compression = encoderinfo["compression"]
  1510. except KeyError:
  1511. compression = im.info.get("compression")
  1512. if isinstance(compression, int):
  1513. # compression value may be from BMP. Ignore it
  1514. compression = None
  1515. if compression is None:
  1516. compression = "raw"
  1517. elif compression == "tiff_jpeg":
  1518. # OJPEG is obsolete, so use new-style JPEG compression instead
  1519. compression = "jpeg"
  1520. elif compression == "tiff_deflate":
  1521. compression = "tiff_adobe_deflate"
  1522. libtiff = WRITE_LIBTIFF or compression != "raw"
  1523. # required for color libtiff images
  1524. ifd[PLANAR_CONFIGURATION] = 1
  1525. ifd[IMAGEWIDTH] = im.size[0]
  1526. ifd[IMAGELENGTH] = im.size[1]
  1527. # write any arbitrary tags passed in as an ImageFileDirectory
  1528. if "tiffinfo" in encoderinfo:
  1529. info = encoderinfo["tiffinfo"]
  1530. elif "exif" in encoderinfo:
  1531. info = encoderinfo["exif"]
  1532. if isinstance(info, bytes):
  1533. exif = Image.Exif()
  1534. exif.load(info)
  1535. info = exif
  1536. else:
  1537. info = {}
  1538. logger.debug("Tiffinfo Keys: %s", list(info))
  1539. if isinstance(info, ImageFileDirectory_v1):
  1540. info = info.to_v2()
  1541. for key in info:
  1542. if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
  1543. ifd[key] = info.get_ifd(key)
  1544. else:
  1545. ifd[key] = info.get(key)
  1546. try:
  1547. ifd.tagtype[key] = info.tagtype[key]
  1548. except Exception:
  1549. pass # might not be an IFD. Might not have populated type
  1550. legacy_ifd = {}
  1551. if hasattr(im, "tag"):
  1552. legacy_ifd = im.tag.to_v2()
  1553. supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
  1554. if supplied_tags.get(PLANAR_CONFIGURATION) == 2 and EXTRASAMPLES in supplied_tags:
  1555. # If the image used separate component planes,
  1556. # then EXTRASAMPLES should be ignored when saving contiguously
  1557. if SAMPLESPERPIXEL in supplied_tags:
  1558. supplied_tags[SAMPLESPERPIXEL] -= len(supplied_tags[EXTRASAMPLES])
  1559. del supplied_tags[EXTRASAMPLES]
  1560. for tag in (
  1561. # IFD offset that may not be correct in the saved image
  1562. EXIFIFD,
  1563. # Determined by the image format and should not be copied from legacy_ifd.
  1564. SAMPLEFORMAT,
  1565. ):
  1566. if tag in supplied_tags:
  1567. del supplied_tags[tag]
  1568. # additions written by Greg Couch, gregc@cgl.ucsf.edu
  1569. # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
  1570. if hasattr(im, "tag_v2"):
  1571. # preserve tags from original TIFF image file
  1572. for key in (
  1573. RESOLUTION_UNIT,
  1574. X_RESOLUTION,
  1575. Y_RESOLUTION,
  1576. IPTC_NAA_CHUNK,
  1577. PHOTOSHOP_CHUNK,
  1578. XMP,
  1579. ):
  1580. if key in im.tag_v2:
  1581. if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (
  1582. TiffTags.BYTE,
  1583. TiffTags.UNDEFINED,
  1584. ):
  1585. del supplied_tags[key]
  1586. else:
  1587. ifd[key] = im.tag_v2[key]
  1588. ifd.tagtype[key] = im.tag_v2.tagtype[key]
  1589. # preserve ICC profile (should also work when saving other formats
  1590. # which support profiles as TIFF) -- 2008-06-06 Florian Hoech
  1591. icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))
  1592. if icc:
  1593. ifd[ICCPROFILE] = icc
  1594. for key, name in [
  1595. (IMAGEDESCRIPTION, "description"),
  1596. (X_RESOLUTION, "resolution"),
  1597. (Y_RESOLUTION, "resolution"),
  1598. (X_RESOLUTION, "x_resolution"),
  1599. (Y_RESOLUTION, "y_resolution"),
  1600. (RESOLUTION_UNIT, "resolution_unit"),
  1601. (SOFTWARE, "software"),
  1602. (DATE_TIME, "date_time"),
  1603. (ARTIST, "artist"),
  1604. (COPYRIGHT, "copyright"),
  1605. ]:
  1606. if name in encoderinfo:
  1607. ifd[key] = encoderinfo[name]
  1608. dpi = encoderinfo.get("dpi")
  1609. if dpi:
  1610. ifd[RESOLUTION_UNIT] = 2
  1611. ifd[X_RESOLUTION] = dpi[0]
  1612. ifd[Y_RESOLUTION] = dpi[1]
  1613. if bits != (1,):
  1614. ifd[BITSPERSAMPLE] = bits
  1615. if len(bits) != 1:
  1616. ifd[SAMPLESPERPIXEL] = len(bits)
  1617. if extra is not None:
  1618. ifd[EXTRASAMPLES] = extra
  1619. if format != 1:
  1620. ifd[SAMPLEFORMAT] = format
  1621. if PHOTOMETRIC_INTERPRETATION not in ifd:
  1622. ifd[PHOTOMETRIC_INTERPRETATION] = photo
  1623. elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:
  1624. if im.mode == "1":
  1625. inverted_im = im.copy()
  1626. px = inverted_im.load()
  1627. if px is not None:
  1628. for y in range(inverted_im.height):
  1629. for x in range(inverted_im.width):
  1630. px[x, y] = 0 if px[x, y] == 255 else 255
  1631. im = inverted_im
  1632. else:
  1633. im = ImageOps.invert(im)
  1634. if im.mode in ["P", "PA"]:
  1635. lut = im.im.getpalette("RGB", "RGB;L")
  1636. colormap = []
  1637. colors = len(lut) // 3
  1638. for i in range(3):
  1639. colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]
  1640. colormap += [0] * (256 - colors)
  1641. ifd[COLORMAP] = colormap
  1642. # data orientation
  1643. w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]
  1644. stride = len(bits) * ((w * bits[0] + 7) // 8)
  1645. if ROWSPERSTRIP not in ifd:
  1646. # aim for given strip size (64 KB by default) when using libtiff writer
  1647. if libtiff:
  1648. im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)
  1649. rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)
  1650. # JPEG encoder expects multiple of 8 rows
  1651. if compression == "jpeg":
  1652. rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)
  1653. else:
  1654. rows_per_strip = h
  1655. if rows_per_strip == 0:
  1656. rows_per_strip = 1
  1657. ifd[ROWSPERSTRIP] = rows_per_strip
  1658. strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]
  1659. strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]
  1660. if strip_byte_counts >= 2**16:
  1661. ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
  1662. ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (
  1663. stride * h - strip_byte_counts * (strips_per_image - 1),
  1664. )
  1665. ifd[STRIPOFFSETS] = tuple(
  1666. range(0, strip_byte_counts * strips_per_image, strip_byte_counts)
  1667. ) # this is adjusted by IFD writer
  1668. # no compression by default:
  1669. ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
  1670. if im.mode == "YCbCr":
  1671. for tag, default_value in {
  1672. YCBCRSUBSAMPLING: (1, 1),
  1673. REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),
  1674. }.items():
  1675. ifd.setdefault(tag, default_value)
  1676. blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]
  1677. if libtiff:
  1678. if "quality" in encoderinfo:
  1679. quality = encoderinfo["quality"]
  1680. if not isinstance(quality, int) or quality < 0 or quality > 100:
  1681. msg = "Invalid quality setting"
  1682. raise ValueError(msg)
  1683. if compression != "jpeg":
  1684. msg = "quality setting only supported for 'jpeg' compression"
  1685. raise ValueError(msg)
  1686. ifd[JPEGQUALITY] = quality
  1687. logger.debug("Saving using libtiff encoder")
  1688. logger.debug("Items: %s", sorted(ifd.items()))
  1689. _fp = 0
  1690. if hasattr(fp, "fileno"):
  1691. try:
  1692. fp.seek(0)
  1693. _fp = fp.fileno()
  1694. except io.UnsupportedOperation:
  1695. pass
  1696. # optional types for non core tags
  1697. types = {}
  1698. # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
  1699. # based on the data in the strip.
  1700. # OSUBFILETYPE is deprecated.
  1701. # TRANSFERFUNCTION is not supported by the libtiff encoder.
  1702. # SUBIFD may also cause a segfault.
  1703. blocklist += [
  1704. OSUBFILETYPE,
  1705. STRIPBYTECOUNTS,
  1706. STRIPOFFSETS,
  1707. TRANSFERFUNCTION,
  1708. SUBIFD,
  1709. ]
  1710. # bits per sample is a single short in the tiff directory, not a list.
  1711. atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
  1712. # Merge the ones that we have with (optional) more bits from
  1713. # the original file, e.g x,y resolution so that we can
  1714. # save(load('')) == original file.
  1715. for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
  1716. # Libtiff can only process certain core items without adding
  1717. # them to the custom dictionary.
  1718. # Custom items are supported for int, float, unicode, string and byte
  1719. # values. Other types and tuples require a tagtype.
  1720. if tag not in TiffTags.LIBTIFF_CORE:
  1721. if tag in TiffTags.TAGS_V2_GROUPS:
  1722. types[tag] = TiffTags.LONG8
  1723. elif tag in ifd.tagtype:
  1724. types[tag] = ifd.tagtype[tag]
  1725. elif isinstance(value, (int, float, str, bytes)) or (
  1726. isinstance(value, tuple)
  1727. and all(isinstance(v, (int, float, IFDRational)) for v in value)
  1728. ):
  1729. type = TiffTags.lookup(tag).type
  1730. if type:
  1731. types[tag] = type
  1732. if tag not in atts and tag not in blocklist:
  1733. if isinstance(value, str):
  1734. atts[tag] = value.encode("ascii", "replace") + b"\0"
  1735. elif isinstance(value, IFDRational):
  1736. atts[tag] = float(value)
  1737. else:
  1738. atts[tag] = value
  1739. if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:
  1740. atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]
  1741. _validate_tags(atts)
  1742. logger.debug("Converted items: %s", sorted(atts.items()))
  1743. # libtiff always expects the bytes in native order.
  1744. # we're storing image byte order. So, if the rawmode
  1745. # contains I;16, we need to convert from native to image
  1746. # byte order.
  1747. if im.mode in ("I;16", "I;16B", "I;16L"):
  1748. rawmode = "I;16N"
  1749. # Pass tags as sorted list so that the tags are set in a fixed order.
  1750. # This is required by libtiff for some tags. For example, the JPEGQUALITY
  1751. # pseudo tag requires that the COMPRESS tag was already set.
  1752. tags = list(atts.items())
  1753. tags.sort()
  1754. a = (rawmode, _fp, filename, tags, types)
  1755. encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
  1756. try:
  1757. encoder.setimage(im.im, (0, 0, *im.size))
  1758. while True:
  1759. errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:]
  1760. if not _fp:
  1761. fp.write(data)
  1762. if errcode:
  1763. break
  1764. if errcode < 0:
  1765. msg = f"encoder error {errcode} when writing image file"
  1766. raise OSError(msg)
  1767. finally:
  1768. encoder.cleanup()
  1769. else:
  1770. for tag in blocklist:
  1771. del ifd[tag]
  1772. _validate_tags(ifd._tags_v2)
  1773. offset = ifd.save(fp)
  1774. ImageFile._save(
  1775. im,
  1776. fp,
  1777. [ImageFile._Tile("raw", (0, 0, *im.size), offset, (rawmode, stride, 1))],
  1778. )
  1779. # -- helper for multi-page save --
  1780. if "_debug_multipage" in encoderinfo:
  1781. # just to access o32 and o16 (using correct byte order)
  1782. setattr(im, "_debug_multipage", ifd)
  1783. class AppendingTiffWriter(io.BytesIO):
  1784. fieldSizes = [
  1785. 0, # None
  1786. 1, # byte
  1787. 1, # ascii
  1788. 2, # short
  1789. 4, # long
  1790. 8, # rational
  1791. 1, # sbyte
  1792. 1, # undefined
  1793. 2, # sshort
  1794. 4, # slong
  1795. 8, # srational
  1796. 4, # float
  1797. 8, # double
  1798. 4, # ifd
  1799. 2, # unicode
  1800. 4, # complex
  1801. 8, # long8
  1802. ]
  1803. Tags = {
  1804. 273, # StripOffsets
  1805. 288, # FreeOffsets
  1806. 324, # TileOffsets
  1807. 519, # JPEGQTables
  1808. 520, # JPEGDCTables
  1809. 521, # JPEGACTables
  1810. }
  1811. def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None:
  1812. self.f: IO[bytes]
  1813. if is_path(fn):
  1814. self.name = fn
  1815. self.close_fp = True
  1816. try:
  1817. self.f = open(fn, "w+b" if new else "r+b")
  1818. except OSError:
  1819. self.f = open(fn, "w+b")
  1820. else:
  1821. self.f = cast("IO[bytes]", fn)
  1822. self.close_fp = False
  1823. self.beginning = self.f.tell()
  1824. self.setup()
  1825. def setup(self) -> None:
  1826. # Reset everything.
  1827. self.f.seek(self.beginning, os.SEEK_SET)
  1828. self.whereToWriteNewIFDOffset: int | None = None
  1829. self.offsetOfNewPage = 0
  1830. self.IIMM = iimm = self.f.read(4)
  1831. self._bigtiff = b"\x2b" in iimm
  1832. if not iimm:
  1833. # empty file - first page
  1834. self.isFirst = True
  1835. return
  1836. self.isFirst = False
  1837. if iimm not in PREFIXES:
  1838. msg = "Invalid TIFF file header"
  1839. raise RuntimeError(msg)
  1840. self.setEndian("<" if iimm.startswith(II) else ">")
  1841. if self._bigtiff:
  1842. self.f.seek(4, os.SEEK_CUR)
  1843. self.skipIFDs()
  1844. self.goToEnd()
  1845. def finalize(self) -> None:
  1846. if self.isFirst:
  1847. return
  1848. # fix offsets
  1849. self.f.seek(self.offsetOfNewPage)
  1850. iimm = self.f.read(4)
  1851. if not iimm:
  1852. # Make it easy to finish a frame without committing to a new one.
  1853. return
  1854. if iimm != self.IIMM:
  1855. msg = "IIMM of new page doesn't match IIMM of first page"
  1856. raise RuntimeError(msg)
  1857. if self._bigtiff:
  1858. self.f.seek(4, os.SEEK_CUR)
  1859. ifd_offset = self._read(8 if self._bigtiff else 4)
  1860. ifd_offset += self.offsetOfNewPage
  1861. assert self.whereToWriteNewIFDOffset is not None
  1862. self.f.seek(self.whereToWriteNewIFDOffset)
  1863. self._write(ifd_offset, 8 if self._bigtiff else 4)
  1864. self.f.seek(ifd_offset)
  1865. self.fixIFD()
  1866. def newFrame(self) -> None:
  1867. # Call this to finish a frame.
  1868. self.finalize()
  1869. self.setup()
  1870. def __enter__(self) -> Self:
  1871. return self
  1872. def __exit__(self, *args: object) -> None:
  1873. if self.close_fp:
  1874. self.close()
  1875. def tell(self) -> int:
  1876. return self.f.tell() - self.offsetOfNewPage
  1877. def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
  1878. """
  1879. :param offset: Distance to seek.
  1880. :param whence: Whether the distance is relative to the start,
  1881. end or current position.
  1882. :returns: The resulting position, relative to the start.
  1883. """
  1884. if whence == os.SEEK_SET:
  1885. offset += self.offsetOfNewPage
  1886. self.f.seek(offset, whence)
  1887. return self.tell()
  1888. def goToEnd(self) -> None:
  1889. self.f.seek(0, os.SEEK_END)
  1890. pos = self.f.tell()
  1891. # pad to 16 byte boundary
  1892. pad_bytes = 16 - pos % 16
  1893. if 0 < pad_bytes < 16:
  1894. self.f.write(bytes(pad_bytes))
  1895. self.offsetOfNewPage = self.f.tell()
  1896. def setEndian(self, endian: str) -> None:
  1897. self.endian = endian
  1898. self.longFmt = f"{self.endian}L"
  1899. self.shortFmt = f"{self.endian}H"
  1900. self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L")
  1901. def skipIFDs(self) -> None:
  1902. while True:
  1903. ifd_offset = self._read(8 if self._bigtiff else 4)
  1904. if ifd_offset == 0:
  1905. self.whereToWriteNewIFDOffset = self.f.tell() - (
  1906. 8 if self._bigtiff else 4
  1907. )
  1908. break
  1909. self.f.seek(ifd_offset)
  1910. num_tags = self._read(8 if self._bigtiff else 2)
  1911. self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR)
  1912. def write(self, data: Buffer, /) -> int:
  1913. return self.f.write(data)
  1914. def _fmt(self, field_size: int) -> str:
  1915. try:
  1916. return {2: "H", 4: "L", 8: "Q"}[field_size]
  1917. except KeyError:
  1918. msg = "offset is not supported"
  1919. raise RuntimeError(msg)
  1920. def _read(self, field_size: int) -> int:
  1921. (value,) = struct.unpack(
  1922. self.endian + self._fmt(field_size), self.f.read(field_size)
  1923. )
  1924. return value
  1925. def readShort(self) -> int:
  1926. return self._read(2)
  1927. def readLong(self) -> int:
  1928. return self._read(4)
  1929. @staticmethod
  1930. def _verify_bytes_written(bytes_written: int | None, expected: int) -> None:
  1931. if bytes_written is not None and bytes_written != expected:
  1932. msg = f"wrote only {bytes_written} bytes but wanted {expected}"
  1933. raise RuntimeError(msg)
  1934. def _rewriteLast(
  1935. self, value: int, field_size: int, new_field_size: int = 0
  1936. ) -> None:
  1937. self.f.seek(-field_size, os.SEEK_CUR)
  1938. if not new_field_size:
  1939. new_field_size = field_size
  1940. bytes_written = self.f.write(
  1941. struct.pack(self.endian + self._fmt(new_field_size), value)
  1942. )
  1943. self._verify_bytes_written(bytes_written, new_field_size)
  1944. def rewriteLastShortToLong(self, value: int) -> None:
  1945. self._rewriteLast(value, 2, 4)
  1946. def rewriteLastShort(self, value: int) -> None:
  1947. return self._rewriteLast(value, 2)
  1948. def rewriteLastLong(self, value: int) -> None:
  1949. return self._rewriteLast(value, 4)
  1950. def _write(self, value: int, field_size: int) -> None:
  1951. bytes_written = self.f.write(
  1952. struct.pack(self.endian + self._fmt(field_size), value)
  1953. )
  1954. self._verify_bytes_written(bytes_written, field_size)
  1955. def writeShort(self, value: int) -> None:
  1956. self._write(value, 2)
  1957. def writeLong(self, value: int) -> None:
  1958. self._write(value, 4)
  1959. def close(self) -> None:
  1960. self.finalize()
  1961. if self.close_fp:
  1962. self.f.close()
  1963. def fixIFD(self) -> None:
  1964. num_tags = self._read(8 if self._bigtiff else 2)
  1965. for i in range(num_tags):
  1966. tag, field_type, count = struct.unpack(
  1967. self.tagFormat, self.f.read(12 if self._bigtiff else 8)
  1968. )
  1969. field_size = self.fieldSizes[field_type]
  1970. total_size = field_size * count
  1971. fmt_size = 8 if self._bigtiff else 4
  1972. is_local = total_size <= fmt_size
  1973. if not is_local:
  1974. offset = self._read(fmt_size) + self.offsetOfNewPage
  1975. self._rewriteLast(offset, fmt_size)
  1976. if tag in self.Tags:
  1977. cur_pos = self.f.tell()
  1978. logger.debug(
  1979. "fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d",
  1980. TiffTags.lookup(tag).name,
  1981. tag,
  1982. TYPES.get(field_type, "unknown"),
  1983. field_type,
  1984. field_size,
  1985. count,
  1986. )
  1987. if is_local:
  1988. self._fixOffsets(count, field_size)
  1989. self.f.seek(cur_pos + fmt_size)
  1990. else:
  1991. self.f.seek(offset)
  1992. self._fixOffsets(count, field_size)
  1993. self.f.seek(cur_pos)
  1994. elif is_local:
  1995. # skip the locally stored value that is not an offset
  1996. self.f.seek(fmt_size, os.SEEK_CUR)
  1997. def _fixOffsets(self, count: int, field_size: int) -> None:
  1998. for i in range(count):
  1999. offset = self._read(field_size)
  2000. offset += self.offsetOfNewPage
  2001. new_field_size = 0
  2002. if self._bigtiff and field_size in (2, 4) and offset >= 2**32:
  2003. # offset is now too large - we must convert long to long8
  2004. new_field_size = 8
  2005. elif field_size == 2 and offset >= 2**16:
  2006. # offset is now too large - we must convert short to long
  2007. new_field_size = 4
  2008. if new_field_size:
  2009. if count != 1:
  2010. msg = "not implemented"
  2011. raise RuntimeError(msg) # XXX TODO
  2012. # simple case - the offset is just one and therefore it is
  2013. # local (not referenced with another offset)
  2014. self._rewriteLast(offset, field_size, new_field_size)
  2015. # Move back past the new offset, past 'count', and before 'field_type'
  2016. rewind = -new_field_size - 4 - 2
  2017. self.f.seek(rewind, os.SEEK_CUR)
  2018. self.writeShort(new_field_size) # rewrite the type
  2019. self.f.seek(2 - rewind, os.SEEK_CUR)
  2020. else:
  2021. self._rewriteLast(offset, field_size)
  2022. def fixOffsets(
  2023. self, count: int, isShort: bool = False, isLong: bool = False
  2024. ) -> None:
  2025. if isShort:
  2026. field_size = 2
  2027. elif isLong:
  2028. field_size = 4
  2029. else:
  2030. field_size = 0
  2031. return self._fixOffsets(count, field_size)
  2032. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  2033. append_images = list(im.encoderinfo.get("append_images", []))
  2034. if not hasattr(im, "n_frames") and not append_images:
  2035. return _save(im, fp, filename)
  2036. cur_idx = im.tell()
  2037. try:
  2038. with AppendingTiffWriter(fp) as tf:
  2039. for ims in [im] + append_images:
  2040. encoderinfo = ims._attach_default_encoderinfo(im)
  2041. if not hasattr(ims, "encoderconfig"):
  2042. ims.encoderconfig = ()
  2043. nfr = getattr(ims, "n_frames", 1)
  2044. for idx in range(nfr):
  2045. ims.seek(idx)
  2046. ims.load()
  2047. _save(ims, tf, filename)
  2048. tf.newFrame()
  2049. ims.encoderinfo = encoderinfo
  2050. finally:
  2051. im.seek(cur_idx)
  2052. #
  2053. # --------------------------------------------------------------------
  2054. # Register
  2055. Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
  2056. Image.register_save(TiffImageFile.format, _save)
  2057. Image.register_save_all(TiffImageFile.format, _save_all)
  2058. Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"])
  2059. Image.register_mime(TiffImageFile.format, "image/tiff")