TiffImagePlugin.py 83 KB

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