TiffImagePlugin.py 75 KB

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