TiffImagePlugin.py 67 KB

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