Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TiffImagePlugin.py 75KB

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