EXIF.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Library to extract EXIF information from digital camera image files
  5. # http://sourceforge.net/projects/exif-py/
  6. #
  7. # VERSION 1.0.7
  8. #
  9. # To use this library call with:
  10. # f = open(path_name, 'rb')
  11. # tags = EXIF.process_file(f)
  12. #
  13. # To ignore makerNote tags, pass the -q or --quick
  14. # command line arguments, or as
  15. # f = open(path_name, 'rb')
  16. # tags = EXIF.process_file(f, details=False)
  17. #
  18. # To stop processing after a certain tag is retrieved,
  19. # pass the -t TAG or --stop-tag TAG argument, or as
  20. # f = open(path_name, 'rb')
  21. # tags = EXIF.process_file(f, stop_tag='TAG')
  22. #
  23. # where TAG is a valid tag name, ex 'DateTimeOriginal'
  24. #
  25. # These are useful when you are retrieving a large list of images
  26. #
  27. # Returned tags will be a dictionary mapping names of EXIF tags to their
  28. # values in the file named by path_name. You can process the tags
  29. # as you wish. In particular, you can iterate through all the tags with:
  30. # for tag in tags.keys():
  31. # if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename',
  32. # 'EXIF MakerNote'):
  33. # print "Key: %s, value %s" % (tag, tags[tag])
  34. # (This code uses the if statement to avoid printing out a few of the
  35. # tags that tend to be long or boring.)
  36. #
  37. # The tags dictionary will include keys for all of the usual EXIF
  38. # tags, and will also include keys for Makernotes used by some
  39. # cameras, for which we have a good specification.
  40. #
  41. # Note that the dictionary keys are the IFD name followed by the
  42. # tag name. For example:
  43. # 'EXIF DateTimeOriginal', 'Image Orientation', 'MakerNote FocusMode'
  44. #
  45. # Copyright (c) 2002-2007 Gene Cash All rights reserved
  46. # Copyright (c) 2007 Ianaré Sévi All rights reserved
  47. #
  48. # Redistribution and use in source and binary forms, with or without
  49. # modification, are permitted provided that the following conditions
  50. # are met:
  51. #
  52. # 1. Redistributions of source code must retain the above copyright
  53. # notice, this list of conditions and the following disclaimer.
  54. #
  55. # 2. Redistributions in binary form must reproduce the above
  56. # copyright notice, this list of conditions and the following
  57. # disclaimer in the documentation and/or other materials provided
  58. # with the distribution.
  59. #
  60. # 3. Neither the name of the authors nor the names of its contributors
  61. # may be used to endorse or promote products derived from this
  62. # software without specific prior written permission.
  63. #
  64. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  65. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  66. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  67. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  68. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  69. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  70. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  71. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  72. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  73. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  74. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  75. #
  76. #
  77. # ----- See 'changes.txt' file for all contributors and changes ----- #
  78. #
  79. # Don't throw an exception when given an out of range character.
  80. def make_string(seq):
  81. str = ""
  82. for c in seq:
  83. # Screen out non-printing characters
  84. if 32 <= c and c < 256:
  85. str += chr(c)
  86. # If no printing chars
  87. if not str:
  88. return seq
  89. return str
  90. # Special version to deal with the code in the first 8 bytes of a user comment.
  91. def make_string_uc(seq):
  92. code = seq[0:8]
  93. seq = seq[8:]
  94. # Of course, this is only correct if ASCII, and the standard explicitly
  95. # allows JIS and Unicode.
  96. return make_string(seq)
  97. # field type descriptions as (length, abbreviation, full name) tuples
  98. FIELD_TYPES = (
  99. (0, "X", "Proprietary"), # no such type
  100. (1, "B", "Byte"),
  101. (1, "A", "ASCII"),
  102. (2, "S", "Short"),
  103. (4, "L", "Long"),
  104. (8, "R", "Ratio"),
  105. (1, "SB", "Signed Byte"),
  106. (1, "U", "Undefined"),
  107. (2, "SS", "Signed Short"),
  108. (4, "SL", "Signed Long"),
  109. (8, "SR", "Signed Ratio"),
  110. )
  111. # dictionary of main EXIF tag names
  112. # first element of tuple is tag name, optional second element is
  113. # another dictionary giving names to values
  114. EXIF_TAGS = {
  115. 0x0100: ("ImageWidth",),
  116. 0x0101: ("ImageLength",),
  117. 0x0102: ("BitsPerSample",),
  118. 0x0103: ("Compression", {1: "Uncompressed TIFF", 6: "JPEG Compressed"}),
  119. 0x0106: ("PhotometricInterpretation",),
  120. 0x010A: ("FillOrder",),
  121. 0x010D: ("DocumentName",),
  122. 0x010E: ("ImageDescription",),
  123. 0x010F: ("Make",),
  124. 0x0110: ("Model",),
  125. 0x0111: ("StripOffsets",),
  126. 0x0112: (
  127. "Orientation",
  128. {
  129. 1: "Horizontal (normal)",
  130. 2: "Mirrored horizontal",
  131. 3: "Rotated 180",
  132. 4: "Mirrored vertical",
  133. 5: "Mirrored horizontal then rotated 90 CCW",
  134. 6: "Rotated 90 CW",
  135. 7: "Mirrored horizontal then rotated 90 CW",
  136. 8: "Rotated 90 CCW",
  137. },
  138. ),
  139. 0x0115: ("SamplesPerPixel",),
  140. 0x0116: ("RowsPerStrip",),
  141. 0x0117: ("StripByteCounts",),
  142. 0x011A: ("XResolution",),
  143. 0x011B: ("YResolution",),
  144. 0x011C: ("PlanarConfiguration",),
  145. 0x0128: (
  146. "ResolutionUnit",
  147. {1: "Not Absolute", 2: "Pixels/Inch", 3: "Pixels/Centimeter"},
  148. ),
  149. 0x012D: ("TransferFunction",),
  150. 0x0131: ("Software",),
  151. 0x0132: ("DateTime",),
  152. 0x013B: ("Artist",),
  153. 0x013E: ("WhitePoint",),
  154. 0x013F: ("PrimaryChromaticities",),
  155. 0x0156: ("TransferRange",),
  156. 0x0200: ("JPEGProc",),
  157. 0x0201: ("JPEGInterchangeFormat",),
  158. 0x0202: ("JPEGInterchangeFormatLength",),
  159. 0x0211: ("YCbCrCoefficients",),
  160. 0x0212: ("YCbCrSubSampling",),
  161. 0x0213: ("YCbCrPositioning",),
  162. 0x0214: ("ReferenceBlackWhite",),
  163. 0x828D: ("CFARepeatPatternDim",),
  164. 0x828E: ("CFAPattern",),
  165. 0x828F: ("BatteryLevel",),
  166. 0x8298: ("Copyright",),
  167. 0x829A: ("ExposureTime",),
  168. 0x829D: ("FNumber",),
  169. 0x83BB: ("IPTC/NAA",),
  170. 0x8769: ("ExifOffset",),
  171. 0x8773: ("InterColorProfile",),
  172. 0x8822: (
  173. "ExposureProgram",
  174. {
  175. 0: "Unidentified",
  176. 1: "Manual",
  177. 2: "Program Normal",
  178. 3: "Aperture Priority",
  179. 4: "Shutter Priority",
  180. 5: "Program Creative",
  181. 6: "Program Action",
  182. 7: "Portrait Mode",
  183. 8: "Landscape Mode",
  184. },
  185. ),
  186. 0x8824: ("SpectralSensitivity",),
  187. 0x8825: ("GPSInfo",),
  188. 0x8827: ("ISOSpeedRatings",),
  189. 0x8828: ("OECF",),
  190. # print as string
  191. 0x9000: ("ExifVersion", make_string),
  192. 0x9003: ("DateTimeOriginal",),
  193. 0x9004: ("DateTimeDigitized",),
  194. 0x9101: (
  195. "ComponentsConfiguration",
  196. {0: "", 1: "Y", 2: "Cb", 3: "Cr", 4: "Red", 5: "Green", 6: "Blue"},
  197. ),
  198. 0x9102: ("CompressedBitsPerPixel",),
  199. 0x9201: ("ShutterSpeedValue",),
  200. 0x9202: ("ApertureValue",),
  201. 0x9203: ("BrightnessValue",),
  202. 0x9204: ("ExposureBiasValue",),
  203. 0x9205: ("MaxApertureValue",),
  204. 0x9206: ("SubjectDistance",),
  205. 0x9207: (
  206. "MeteringMode",
  207. {
  208. 0: "Unidentified",
  209. 1: "Average",
  210. 2: "CenterWeightedAverage",
  211. 3: "Spot",
  212. 4: "MultiSpot",
  213. },
  214. ),
  215. 0x9208: (
  216. "LightSource",
  217. {
  218. 0: "Unknown",
  219. 1: "Daylight",
  220. 2: "Fluorescent",
  221. 3: "Tungsten",
  222. 10: "Flash",
  223. 17: "Standard Light A",
  224. 18: "Standard Light B",
  225. 19: "Standard Light C",
  226. 20: "D55",
  227. 21: "D65",
  228. 22: "D75",
  229. 255: "Other",
  230. },
  231. ),
  232. 0x9209: (
  233. "Flash",
  234. {
  235. 0: "No",
  236. 1: "Fired",
  237. 5: "Fired (?)", # no return sensed
  238. 7: "Fired (!)", # return sensed
  239. 9: "Fill Fired",
  240. 13: "Fill Fired (?)",
  241. 15: "Fill Fired (!)",
  242. 16: "Off",
  243. 24: "Auto Off",
  244. 25: "Auto Fired",
  245. 29: "Auto Fired (?)",
  246. 31: "Auto Fired (!)",
  247. 32: "Not Available",
  248. },
  249. ),
  250. 0x920A: ("FocalLength",),
  251. 0x9214: ("SubjectArea",),
  252. 0x927C: ("MakerNote",),
  253. # print as string
  254. 0x9286: (
  255. "UserComment",
  256. make_string_uc,
  257. ), # First 8 bytes gives coding system e.g. ASCII vs. JIS vs Unicode
  258. 0x9290: ("SubSecTime",),
  259. 0x9291: ("SubSecTimeOriginal",),
  260. 0x9292: ("SubSecTimeDigitized",),
  261. # print as string
  262. 0xA000: ("FlashPixVersion", make_string),
  263. 0xA001: ("ColorSpace",),
  264. 0xA002: ("ExifImageWidth",),
  265. 0xA003: ("ExifImageLength",),
  266. 0xA005: ("InteroperabilityOffset",),
  267. 0xA20B: ("FlashEnergy",), # 0x920B in TIFF/EP
  268. 0xA20C: ("SpatialFrequencyResponse",), # 0x920C - -
  269. 0xA20E: ("FocalPlaneXResolution",), # 0x920E - -
  270. 0xA20F: ("FocalPlaneYResolution",), # 0x920F - -
  271. 0xA210: ("FocalPlaneResolutionUnit",), # 0x9210 - -
  272. 0xA214: ("SubjectLocation",), # 0x9214 - -
  273. 0xA215: ("ExposureIndex",), # 0x9215 - -
  274. 0xA217: ("SensingMethod",), # 0x9217 - -
  275. 0xA300: ("FileSource", {3: "Digital Camera"}),
  276. 0xA301: ("SceneType", {1: "Directly Photographed"}),
  277. 0xA302: ("CVAPattern",),
  278. 0xA401: ("CustomRendered",),
  279. 0xA402: (
  280. "ExposureMode",
  281. {0: "Auto Exposure", 1: "Manual Exposure", 2: "Auto Bracket"},
  282. ),
  283. 0xA403: ("WhiteBalance", {0: "Auto", 1: "Manual"}),
  284. 0xA404: ("DigitalZoomRatio",),
  285. 0xA405: ("FocalLengthIn35mm",),
  286. 0xA406: ("SceneCaptureType",),
  287. 0xA407: ("GainControl",),
  288. 0xA408: ("Contrast",),
  289. 0xA409: ("Saturation",),
  290. 0xA40A: ("Sharpness",),
  291. 0xA40C: ("SubjectDistanceRange",),
  292. }
  293. # interoperability tags
  294. INTR_TAGS = {
  295. 0x0001: ("InteroperabilityIndex",),
  296. 0x0002: ("InteroperabilityVersion",),
  297. 0x1000: ("RelatedImageFileFormat",),
  298. 0x1001: ("RelatedImageWidth",),
  299. 0x1002: ("RelatedImageLength",),
  300. }
  301. # GPS tags (not used yet, haven't seen camera with GPS)
  302. GPS_TAGS = {
  303. 0x0000: ("GPSVersionID",),
  304. 0x0001: ("GPSLatitudeRef",),
  305. 0x0002: ("GPSLatitude",),
  306. 0x0003: ("GPSLongitudeRef",),
  307. 0x0004: ("GPSLongitude",),
  308. 0x0005: ("GPSAltitudeRef",),
  309. 0x0006: ("GPSAltitude",),
  310. 0x0007: ("GPSTimeStamp",),
  311. 0x0008: ("GPSSatellites",),
  312. 0x0009: ("GPSStatus",),
  313. 0x000A: ("GPSMeasureMode",),
  314. 0x000B: ("GPSDOP",),
  315. 0x000C: ("GPSSpeedRef",),
  316. 0x000D: ("GPSSpeed",),
  317. 0x000E: ("GPSTrackRef",),
  318. 0x000F: ("GPSTrack",),
  319. 0x0010: ("GPSImgDirectionRef",),
  320. 0x0011: ("GPSImgDirection",),
  321. 0x0012: ("GPSMapDatum",),
  322. 0x0013: ("GPSDestLatitudeRef",),
  323. 0x0014: ("GPSDestLatitude",),
  324. 0x0015: ("GPSDestLongitudeRef",),
  325. 0x0016: ("GPSDestLongitude",),
  326. 0x0017: ("GPSDestBearingRef",),
  327. 0x0018: ("GPSDestBearing",),
  328. 0x0019: ("GPSDestDistanceRef",),
  329. 0x001A: ("GPSDestDistance",),
  330. }
  331. # Ignore these tags when quick processing
  332. # 0x927C is MakerNote Tags
  333. # 0x9286 is user
  334. IGNORE_TAGS = (0x9286, 0x927C)
  335. # http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp
  336. def nikon_ev_bias(seq):
  337. # First digit seems to be in steps of 1/6 EV.
  338. # Does the third value mean the step size? It is usually 6,
  339. # but it is 12 for the ExposureDifference.
  340. #
  341. if seq == [252, 1, 6, 0]:
  342. return "-2/3 EV"
  343. if seq == [253, 1, 6, 0]:
  344. return "-1/2 EV"
  345. if seq == [254, 1, 6, 0]:
  346. return "-1/3 EV"
  347. if seq == [0, 1, 6, 0]:
  348. return "0 EV"
  349. if seq == [2, 1, 6, 0]:
  350. return "+1/3 EV"
  351. if seq == [3, 1, 6, 0]:
  352. return "+1/2 EV"
  353. if seq == [4, 1, 6, 0]:
  354. return "+2/3 EV"
  355. # Handle combinations not in the table.
  356. a = seq[0]
  357. # Causes headaches for the +/- logic, so special case it.
  358. if a == 0:
  359. return "0 EV"
  360. if a > 127:
  361. a = 256 - a
  362. ret_str = "-"
  363. else:
  364. ret_str = "+"
  365. b = seq[2] # Assume third value means the step size
  366. whole = a / b
  367. a = a % b
  368. if whole != 0:
  369. ret_str = ret_str + str(whole) + " "
  370. if a == 0:
  371. ret_str = ret_str + "EV"
  372. else:
  373. r = Ratio(a, b)
  374. ret_str = ret_str + r.__repr__() + " EV"
  375. return ret_str
  376. # Nikon E99x MakerNote Tags
  377. MAKERNOTE_NIKON_NEWER_TAGS = {
  378. 0x0001: ("MakernoteVersion", make_string), # Sometimes binary
  379. 0x0002: ("ISOSetting",),
  380. 0x0003: ("ColorMode",),
  381. 0x0004: ("Quality",),
  382. 0x0005: ("Whitebalance",),
  383. 0x0006: ("ImageSharpening",),
  384. 0x0007: ("FocusMode",),
  385. 0x0008: ("FlashSetting",),
  386. 0x0009: ("AutoFlashMode",),
  387. 0x000B: ("WhiteBalanceBias",),
  388. 0x000C: ("WhiteBalanceRBCoeff",),
  389. 0x000D: ("ProgramShift", nikon_ev_bias),
  390. # Nearly the same as the other EV vals, but step size is 1/12 EV (?)
  391. 0x000E: ("ExposureDifference", nikon_ev_bias),
  392. 0x000F: ("ISOSelection",),
  393. 0x0011: ("NikonPreview",),
  394. 0x0012: ("FlashCompensation", nikon_ev_bias),
  395. 0x0013: ("ISOSpeedRequested",),
  396. 0x0016: ("PhotoCornerCoordinates",),
  397. # 0x0017: Unknown, but most likely an EV value
  398. 0x0018: ("FlashBracketCompensationApplied", nikon_ev_bias),
  399. 0x0019: ("AEBracketCompensationApplied",),
  400. 0x001A: ("ImageProcessing",),
  401. 0x0080: ("ImageAdjustment",),
  402. 0x0081: ("ToneCompensation",),
  403. 0x0082: ("AuxiliaryLens",),
  404. 0x0083: ("LensType",),
  405. 0x0084: ("LensMinMaxFocalMaxAperture",),
  406. 0x0085: ("ManualFocusDistance",),
  407. 0x0086: ("DigitalZoomFactor",),
  408. 0x0087: (
  409. "FlashMode",
  410. {
  411. 0x00: "Did Not Fire",
  412. 0x01: "Fired, Manual",
  413. 0x07: "Fired, External",
  414. 0x08: "Fired, Commander Mode ",
  415. 0x09: "Fired, TTL Mode",
  416. },
  417. ),
  418. 0x0088: (
  419. "AFFocusPosition",
  420. {
  421. 0x0000: "Center",
  422. 0x0100: "Top",
  423. 0x0200: "Bottom",
  424. 0x0300: "Left",
  425. 0x0400: "Right",
  426. },
  427. ),
  428. 0x0089: (
  429. "BracketingMode",
  430. {
  431. 0x00: "Single frame, no bracketing",
  432. 0x01: "Continuous, no bracketing",
  433. 0x02: "Timer, no bracketing",
  434. 0x10: "Single frame, exposure bracketing",
  435. 0x11: "Continuous, exposure bracketing",
  436. 0x12: "Timer, exposure bracketing",
  437. 0x40: "Single frame, white balance bracketing",
  438. 0x41: "Continuous, white balance bracketing",
  439. 0x42: "Timer, white balance bracketing",
  440. },
  441. ),
  442. 0x008A: ("AutoBracketRelease",),
  443. 0x008B: ("LensFStops",),
  444. 0x008C: ("NEFCurve2",),
  445. 0x008D: ("ColorMode",),
  446. 0x008F: ("SceneMode",),
  447. 0x0090: ("LightingType",),
  448. 0x0091: ("ShotInfo",), # First 4 bytes are probably a version number in ASCII
  449. 0x0092: ("HueAdjustment",),
  450. # 0x0093: ('SaturationAdjustment', ),
  451. 0x0094: (
  452. "Saturation", # Name conflict with 0x00AA !!
  453. {-3: "B&W", -2: "-2", -1: "-1", 0: "0", 1: "1", 2: "2"},
  454. ),
  455. 0x0095: ("NoiseReduction",),
  456. 0x0096: ("NEFCurve2",),
  457. 0x0097: ("ColorBalance",),
  458. 0x0098: ("LensData",), # First 4 bytes are a version number in ASCII
  459. 0x0099: ("RawImageCenter",),
  460. 0x009A: ("SensorPixelSize",),
  461. 0x009C: ("Scene Assist",),
  462. 0x00A0: ("SerialNumber",),
  463. 0x00A2: ("ImageDataSize",),
  464. # A4: In NEF, looks like a 4 byte ASCII version number
  465. 0x00A5: ("ImageCount",),
  466. 0x00A6: ("DeletedImageCount",),
  467. 0x00A7: ("TotalShutterReleases",),
  468. # A8: ExposureMode? JPG: First 4 bytes are probably a version number in ASCII
  469. # But in a sample NEF, its 8 zeros, then the string "NORMAL"
  470. 0x00A9: ("ImageOptimization",),
  471. 0x00AA: ("Saturation",),
  472. 0x00AB: ("DigitalVariProgram",),
  473. 0x00AC: ("ImageStabilization",),
  474. 0x00AD: ("Responsive AF",), # 'AFResponse'
  475. 0x0010: ("DataDump",),
  476. }
  477. MAKERNOTE_NIKON_OLDER_TAGS = {
  478. 0x0003: (
  479. "Quality",
  480. {
  481. 1: "VGA Basic",
  482. 2: "VGA Normal",
  483. 3: "VGA Fine",
  484. 4: "SXGA Basic",
  485. 5: "SXGA Normal",
  486. 6: "SXGA Fine",
  487. },
  488. ),
  489. 0x0004: ("ColorMode", {1: "Color", 2: "Monochrome"}),
  490. 0x0005: (
  491. "ImageAdjustment",
  492. {0: "Normal", 1: "Bright+", 2: "Bright-", 3: "Contrast+", 4: "Contrast-"},
  493. ),
  494. 0x0006: ("CCDSpeed", {0: "ISO 80", 2: "ISO 160", 4: "ISO 320", 5: "ISO 100"}),
  495. 0x0007: (
  496. "WhiteBalance",
  497. {
  498. 0: "Auto",
  499. 1: "Preset",
  500. 2: "Daylight",
  501. 3: "Incandescent",
  502. 4: "Fluorescent",
  503. 5: "Cloudy",
  504. 6: "Speed Light",
  505. },
  506. ),
  507. }
  508. # decode Olympus SpecialMode tag in MakerNote
  509. def olympus_special_mode(v):
  510. a = {0: "Normal", 1: "Unknown", 2: "Fast", 3: "Panorama"}
  511. b = {
  512. 0: "Non-panoramic",
  513. 1: "Left to right",
  514. 2: "Right to left",
  515. 3: "Bottom to top",
  516. 4: "Top to bottom",
  517. }
  518. if v[0] not in a or v[2] not in b:
  519. return v
  520. return "%s - sequence %d - %s" % (a[v[0]], v[1], b[v[2]])
  521. MAKERNOTE_OLYMPUS_TAGS = {
  522. # ah HAH! those sneeeeeaky bastids! this is how they get past the fact
  523. # that a JPEG thumbnail is not allowed in an uncompressed TIFF file
  524. 0x0100: ("JPEGThumbnail",),
  525. 0x0200: ("SpecialMode", olympus_special_mode),
  526. 0x0201: ("JPEGQual", {1: "SQ", 2: "HQ", 3: "SHQ"}),
  527. 0x0202: ("Macro", {0: "Normal", 1: "Macro", 2: "SuperMacro"}),
  528. 0x0203: ("BWMode", {0: "Off", 1: "On"}),
  529. 0x0204: ("DigitalZoom",),
  530. 0x0205: ("FocalPlaneDiagonal",),
  531. 0x0206: ("LensDistortionParams",),
  532. 0x0207: ("SoftwareRelease",),
  533. 0x0208: ("PictureInfo",),
  534. 0x0209: ("CameraID", make_string), # print as string
  535. 0x0F00: ("DataDump",),
  536. 0x0300: ("PreCaptureFrames",),
  537. 0x0404: ("SerialNumber",),
  538. 0x1000: ("ShutterSpeedValue",),
  539. 0x1001: ("ISOValue",),
  540. 0x1002: ("ApertureValue",),
  541. 0x1003: ("BrightnessValue",),
  542. 0x1004: ("FlashMode",),
  543. 0x1004: ("FlashMode", {2: "On", 3: "Off"}),
  544. 0x1005: (
  545. "FlashDevice",
  546. {0: "None", 1: "Internal", 4: "External", 5: "Internal + External"},
  547. ),
  548. 0x1006: ("ExposureCompensation",),
  549. 0x1007: ("SensorTemperature",),
  550. 0x1008: ("LensTemperature",),
  551. 0x100B: ("FocusMode", {0: "Auto", 1: "Manual"}),
  552. 0x1017: ("RedBalance",),
  553. 0x1018: ("BlueBalance",),
  554. 0x101A: ("SerialNumber",),
  555. 0x1023: ("FlashExposureComp",),
  556. 0x1026: ("ExternalFlashBounce", {0: "No", 1: "Yes"}),
  557. 0x1027: ("ExternalFlashZoom",),
  558. 0x1028: ("ExternalFlashMode",),
  559. 0x1029: ("Contrast int16u", {0: "High", 1: "Normal", 2: "Low"}),
  560. 0x102A: ("SharpnessFactor",),
  561. 0x102B: ("ColorControl",),
  562. 0x102C: ("ValidBits",),
  563. 0x102D: ("CoringFilter",),
  564. 0x102E: ("OlympusImageWidth",),
  565. 0x102F: ("OlympusImageHeight",),
  566. 0x1034: ("CompressionRatio",),
  567. 0x1035: ("PreviewImageValid", {0: "No", 1: "Yes"}),
  568. 0x1036: ("PreviewImageStart",),
  569. 0x1037: ("PreviewImageLength",),
  570. 0x1039: ("CCDScanMode", {0: "Interlaced", 1: "Progressive"}),
  571. 0x103A: ("NoiseReduction", {0: "Off", 1: "On"}),
  572. 0x103B: ("InfinityLensStep",),
  573. 0x103C: ("NearLensStep",),
  574. # TODO - these need extra definitions
  575. # http://search.cpan.org/src/EXIFTOOL/Image-ExifTool-6.90/html/TagNames/Olympus.html
  576. 0x2010: ("Equipment",),
  577. 0x2020: ("CameraSettings",),
  578. 0x2030: ("RawDevelopment",),
  579. 0x2040: ("ImageProcessing",),
  580. 0x2050: ("FocusInfo",),
  581. 0x3000: ("RawInfo ",),
  582. }
  583. # 0x2020 CameraSettings
  584. MAKERNOTE_OLYMPUS_TAG_0x2020 = {
  585. 0x0100: ("PreviewImageValid", {0: "No", 1: "Yes"}),
  586. 0x0101: ("PreviewImageStart",),
  587. 0x0102: ("PreviewImageLength",),
  588. 0x0200: (
  589. "ExposureMode",
  590. {
  591. 1: "Manual",
  592. 2: "Program",
  593. 3: "Aperture-priority AE",
  594. 4: "Shutter speed priority AE",
  595. 5: "Program-shift",
  596. },
  597. ),
  598. 0x0201: ("AELock", {0: "Off", 1: "On"}),
  599. 0x0202: (
  600. "MeteringMode",
  601. {
  602. 2: "Center Weighted",
  603. 3: "Spot",
  604. 5: "ESP",
  605. 261: "Pattern+AF",
  606. 515: "Spot+Highlight control",
  607. 1027: "Spot+Shadow control",
  608. },
  609. ),
  610. 0x0300: ("MacroMode", {0: "Off", 1: "On"}),
  611. 0x0301: (
  612. "FocusMode",
  613. {
  614. 0: "Single AF",
  615. 1: "Sequential shooting AF",
  616. 2: "Continuous AF",
  617. 3: "Multi AF",
  618. 10: "MF",
  619. },
  620. ),
  621. 0x0302: ("FocusProcess", {0: "AF Not Used", 1: "AF Used"}),
  622. 0x0303: ("AFSearch", {0: "Not Ready", 1: "Ready"}),
  623. 0x0304: ("AFAreas",),
  624. 0x0401: ("FlashExposureCompensation",),
  625. 0x0500: (
  626. "WhiteBalance2",
  627. {
  628. 0: "Auto",
  629. 16: "7500K (Fine Weather with Shade)",
  630. 17: "6000K (Cloudy)",
  631. 18: "5300K (Fine Weather)",
  632. 20: "3000K (Tungsten light)",
  633. 21: "3600K (Tungsten light-like)",
  634. 33: "6600K (Daylight fluorescent)",
  635. 34: "4500K (Neutral white fluorescent)",
  636. 35: "4000K (Cool white fluorescent)",
  637. 48: "3600K (Tungsten light-like)",
  638. 256: "Custom WB 1",
  639. 257: "Custom WB 2",
  640. 258: "Custom WB 3",
  641. 259: "Custom WB 4",
  642. 512: "Custom WB 5400K",
  643. 513: "Custom WB 2900K",
  644. 514: "Custom WB 8000K",
  645. },
  646. ),
  647. 0x0501: ("WhiteBalanceTemperature",),
  648. 0x0502: ("WhiteBalanceBracket",),
  649. 0x0503: ("CustomSaturation",), # (3 numbers: 1. CS Value, 2. Min, 3. Max)
  650. 0x0504: (
  651. "ModifiedSaturation",
  652. {
  653. 0: "Off",
  654. 1: "CM1 (Red Enhance)",
  655. 2: "CM2 (Green Enhance)",
  656. 3: "CM3 (Blue Enhance)",
  657. 4: "CM4 (Skin Tones)",
  658. },
  659. ),
  660. 0x0505: ("ContrastSetting",), # (3 numbers: 1. Contrast, 2. Min, 3. Max)
  661. 0x0506: ("SharpnessSetting",), # (3 numbers: 1. Sharpness, 2. Min, 3. Max)
  662. 0x0507: ("ColorSpace", {0: "sRGB", 1: "Adobe RGB", 2: "Pro Photo RGB"}),
  663. 0x0509: (
  664. "SceneMode",
  665. {
  666. 0: "Standard",
  667. 6: "Auto",
  668. 7: "Sport",
  669. 8: "Portrait",
  670. 9: "Landscape+Portrait",
  671. 10: "Landscape",
  672. 11: "Night scene",
  673. 13: "Panorama",
  674. 16: "Landscape+Portrait",
  675. 17: "Night+Portrait",
  676. 19: "Fireworks",
  677. 20: "Sunset",
  678. 22: "Macro",
  679. 25: "Documents",
  680. 26: "Museum",
  681. 28: "Beach&Snow",
  682. 30: "Candle",
  683. 35: "Underwater Wide1",
  684. 36: "Underwater Macro",
  685. 39: "High Key",
  686. 40: "Digital Image Stabilization",
  687. 44: "Underwater Wide2",
  688. 45: "Low Key",
  689. 46: "Children",
  690. 48: "Nature Macro",
  691. },
  692. ),
  693. 0x050A: (
  694. "NoiseReduction",
  695. {
  696. 0: "Off",
  697. 1: "Noise Reduction",
  698. 2: "Noise Filter",
  699. 3: "Noise Reduction + Noise Filter",
  700. 4: "Noise Filter (ISO Boost)",
  701. 5: "Noise Reduction + Noise Filter (ISO Boost)",
  702. },
  703. ),
  704. 0x050B: ("DistortionCorrection", {0: "Off", 1: "On"}),
  705. 0x050C: ("ShadingCompensation", {0: "Off", 1: "On"}),
  706. 0x050D: ("CompressionFactor",),
  707. 0x050F: (
  708. "Gradation",
  709. {"-1 -1 1": "Low Key", "0 -1 1": "Normal", "1 -1 1": "High Key"},
  710. ),
  711. 0x0520: (
  712. "PictureMode",
  713. {1: "Vivid", 2: "Natural", 3: "Muted", 256: "Monotone", 512: "Sepia"},
  714. ),
  715. 0x0521: ("PictureModeSaturation",),
  716. 0x0522: ("PictureModeHue?",),
  717. 0x0523: ("PictureModeContrast",),
  718. 0x0524: ("PictureModeSharpness",),
  719. 0x0525: (
  720. "PictureModeBWFilter",
  721. {0: "n/a", 1: "Neutral", 2: "Yellow", 3: "Orange", 4: "Red", 5: "Green"},
  722. ),
  723. 0x0526: (
  724. "PictureModeTone",
  725. {0: "n/a", 1: "Neutral", 2: "Sepia", 3: "Blue", 4: "Purple", 5: "Green"},
  726. ),
  727. 0x0600: ("Sequence",), # 2 or 3 numbers: 1. Mode, 2. Shot number, 3. Mode bits
  728. 0x0601: ("PanoramaMode",), # (2 numbers: 1. Mode, 2. Shot number)
  729. 0x0603: ("ImageQuality2", {1: "SQ", 2: "HQ", 3: "SHQ", 4: "RAW"}),
  730. 0x0901: ("ManometerReading",),
  731. }
  732. MAKERNOTE_CASIO_TAGS = {
  733. 0x0001: (
  734. "RecordingMode",
  735. {
  736. 1: "Single Shutter",
  737. 2: "Panorama",
  738. 3: "Night Scene",
  739. 4: "Portrait",
  740. 5: "Landscape",
  741. },
  742. ),
  743. 0x0002: ("Quality", {1: "Economy", 2: "Normal", 3: "Fine"}),
  744. 0x0003: (
  745. "FocusingMode",
  746. {2: "Macro", 3: "Auto Focus", 4: "Manual Focus", 5: "Infinity"},
  747. ),
  748. 0x0004: ("FlashMode", {1: "Auto", 2: "On", 3: "Off", 4: "Red Eye Reduction"}),
  749. 0x0005: ("FlashIntensity", {11: "Weak", 13: "Normal", 15: "Strong"}),
  750. 0x0006: ("Object Distance",),
  751. 0x0007: (
  752. "WhiteBalance",
  753. {
  754. 1: "Auto",
  755. 2: "Tungsten",
  756. 3: "Daylight",
  757. 4: "Fluorescent",
  758. 5: "Shade",
  759. 129: "Manual",
  760. },
  761. ),
  762. 0x000B: ("Sharpness", {0: "Normal", 1: "Soft", 2: "Hard"}),
  763. 0x000C: ("Contrast", {0: "Normal", 1: "Low", 2: "High"}),
  764. 0x000D: ("Saturation", {0: "Normal", 1: "Low", 2: "High"}),
  765. 0x0014: (
  766. "CCDSpeed",
  767. {
  768. 64: "Normal",
  769. 80: "Normal",
  770. 100: "High",
  771. 125: "+1.0",
  772. 244: "+3.0",
  773. 250: "+2.0",
  774. },
  775. ),
  776. }
  777. MAKERNOTE_FUJIFILM_TAGS = {
  778. 0x0000: ("NoteVersion", make_string),
  779. 0x1000: ("Quality",),
  780. 0x1001: ("Sharpness", {1: "Soft", 2: "Soft", 3: "Normal", 4: "Hard", 5: "Hard"}),
  781. 0x1002: (
  782. "WhiteBalance",
  783. {
  784. 0: "Auto",
  785. 256: "Daylight",
  786. 512: "Cloudy",
  787. 768: "DaylightColor-Fluorescent",
  788. 769: "DaywhiteColor-Fluorescent",
  789. 770: "White-Fluorescent",
  790. 1024: "Incandescent",
  791. 3840: "Custom",
  792. },
  793. ),
  794. 0x1003: ("Color", {0: "Normal", 256: "High", 512: "Low"}),
  795. 0x1004: ("Tone", {0: "Normal", 256: "High", 512: "Low"}),
  796. 0x1010: ("FlashMode", {0: "Auto", 1: "On", 2: "Off", 3: "Red Eye Reduction"}),
  797. 0x1011: ("FlashStrength",),
  798. 0x1020: ("Macro", {0: "Off", 1: "On"}),
  799. 0x1021: ("FocusMode", {0: "Auto", 1: "Manual"}),
  800. 0x1030: ("SlowSync", {0: "Off", 1: "On"}),
  801. 0x1031: (
  802. "PictureMode",
  803. {
  804. 0: "Auto",
  805. 1: "Portrait",
  806. 2: "Landscape",
  807. 4: "Sports",
  808. 5: "Night",
  809. 6: "Program AE",
  810. 256: "Aperture Priority AE",
  811. 512: "Shutter Priority AE",
  812. 768: "Manual Exposure",
  813. },
  814. ),
  815. 0x1100: ("MotorOrBracket", {0: "Off", 1: "On"}),
  816. 0x1300: ("BlurWarning", {0: "Off", 1: "On"}),
  817. 0x1301: ("FocusWarning", {0: "Off", 1: "On"}),
  818. 0x1302: ("AEWarning", {0: "Off", 1: "On"}),
  819. }
  820. MAKERNOTE_CANON_TAGS = {
  821. 0x0006: ("ImageType",),
  822. 0x0007: ("FirmwareVersion",),
  823. 0x0008: ("ImageNumber",),
  824. 0x0009: ("OwnerName",),
  825. }
  826. # this is in element offset, name, optional value dictionary format
  827. MAKERNOTE_CANON_TAG_0x001 = {
  828. 1: ("Macromode", {1: "Macro", 2: "Normal"}),
  829. 2: ("SelfTimer",),
  830. 3: ("Quality", {2: "Normal", 3: "Fine", 5: "Superfine"}),
  831. 4: (
  832. "FlashMode",
  833. {
  834. 0: "Flash Not Fired",
  835. 1: "Auto",
  836. 2: "On",
  837. 3: "Red-Eye Reduction",
  838. 4: "Slow Synchro",
  839. 5: "Auto + Red-Eye Reduction",
  840. 6: "On + Red-Eye Reduction",
  841. 16: "external flash",
  842. },
  843. ),
  844. 5: ("ContinuousDriveMode", {0: "Single Or Timer", 1: "Continuous"}),
  845. 7: (
  846. "FocusMode",
  847. {
  848. 0: "One-Shot",
  849. 1: "AI Servo",
  850. 2: "AI Focus",
  851. 3: "MF",
  852. 4: "Single",
  853. 5: "Continuous",
  854. 6: "MF",
  855. },
  856. ),
  857. 10: ("ImageSize", {0: "Large", 1: "Medium", 2: "Small"}),
  858. 11: (
  859. "EasyShootingMode",
  860. {
  861. 0: "Full Auto",
  862. 1: "Manual",
  863. 2: "Landscape",
  864. 3: "Fast Shutter",
  865. 4: "Slow Shutter",
  866. 5: "Night",
  867. 6: "B&W",
  868. 7: "Sepia",
  869. 8: "Portrait",
  870. 9: "Sports",
  871. 10: "Macro/Close-Up",
  872. 11: "Pan Focus",
  873. },
  874. ),
  875. 12: ("DigitalZoom", {0: "None", 1: "2x", 2: "4x"}),
  876. 13: ("Contrast", {0xFFFF: "Low", 0: "Normal", 1: "High"}),
  877. 14: ("Saturation", {0xFFFF: "Low", 0: "Normal", 1: "High"}),
  878. 15: ("Sharpness", {0xFFFF: "Low", 0: "Normal", 1: "High"}),
  879. 16: (
  880. "ISO",
  881. {
  882. 0: "See ISOSpeedRatings Tag",
  883. 15: "Auto",
  884. 16: "50",
  885. 17: "100",
  886. 18: "200",
  887. 19: "400",
  888. },
  889. ),
  890. 17: ("MeteringMode", {3: "Evaluative", 4: "Partial", 5: "Center-weighted"}),
  891. 18: (
  892. "FocusType",
  893. {0: "Manual", 1: "Auto", 3: "Close-Up (Macro)", 8: "Locked (Pan Mode)"},
  894. ),
  895. 19: (
  896. "AFPointSelected",
  897. {
  898. 0x3000: "None (MF)",
  899. 0x3001: "Auto-Selected",
  900. 0x3002: "Right",
  901. 0x3003: "Center",
  902. 0x3004: "Left",
  903. },
  904. ),
  905. 20: (
  906. "ExposureMode",
  907. {
  908. 0: "Easy Shooting",
  909. 1: "Program",
  910. 2: "Tv-priority",
  911. 3: "Av-priority",
  912. 4: "Manual",
  913. 5: "A-DEP",
  914. },
  915. ),
  916. 23: ("LongFocalLengthOfLensInFocalUnits",),
  917. 24: ("ShortFocalLengthOfLensInFocalUnits",),
  918. 25: ("FocalUnitsPerMM",),
  919. 28: ("FlashActivity", {0: "Did Not Fire", 1: "Fired"}),
  920. 29: (
  921. "FlashDetails",
  922. {
  923. 14: "External E-TTL",
  924. 13: "Internal Flash",
  925. 11: "FP Sync Used",
  926. 7: '2nd("Rear")-Curtain Sync Used',
  927. 4: "FP Sync Enabled",
  928. },
  929. ),
  930. 32: ("FocusMode", {0: "Single", 1: "Continuous"}),
  931. }
  932. MAKERNOTE_CANON_TAG_0x004 = {
  933. 7: (
  934. "WhiteBalance",
  935. {
  936. 0: "Auto",
  937. 1: "Sunny",
  938. 2: "Cloudy",
  939. 3: "Tungsten",
  940. 4: "Fluorescent",
  941. 5: "Flash",
  942. 6: "Custom",
  943. },
  944. ),
  945. 9: ("SequenceNumber",),
  946. 14: ("AFPointUsed",),
  947. 15: (
  948. "FlashBias",
  949. {
  950. 0xFFC0: "-2 EV",
  951. 0xFFCC: "-1.67 EV",
  952. 0xFFD0: "-1.50 EV",
  953. 0xFFD4: "-1.33 EV",
  954. 0xFFE0: "-1 EV",
  955. 0xFFEC: "-0.67 EV",
  956. 0xFFF0: "-0.50 EV",
  957. 0xFFF4: "-0.33 EV",
  958. 0x0000: "0 EV",
  959. 0x000C: "0.33 EV",
  960. 0x0010: "0.50 EV",
  961. 0x0014: "0.67 EV",
  962. 0x0020: "1 EV",
  963. 0x002C: "1.33 EV",
  964. 0x0030: "1.50 EV",
  965. 0x0034: "1.67 EV",
  966. 0x0040: "2 EV",
  967. },
  968. ),
  969. 19: ("SubjectDistance",),
  970. }
  971. # extract multibyte integer in Motorola format (little endian)
  972. def s2n_motorola(str):
  973. x = 0
  974. for c in str:
  975. x = (x << 8) | ord(c)
  976. return x
  977. # extract multibyte integer in Intel format (big endian)
  978. def s2n_intel(str):
  979. x = 0
  980. y = 0L
  981. for c in str:
  982. x = x | (ord(c) << y)
  983. y = y + 8
  984. return x
  985. # ratio object that eventually will be able to reduce itself to lowest
  986. # common denominator for printing
  987. def gcd(a, b):
  988. if b == 0:
  989. return a
  990. else:
  991. return gcd(b, a % b)
  992. class Ratio:
  993. def __init__(self, num, den):
  994. self.num = num
  995. self.den = den
  996. def __repr__(self):
  997. self.reduce()
  998. if self.den == 1:
  999. return str(self.num)
  1000. return "%d/%d" % (self.num, self.den)
  1001. def reduce(self):
  1002. div = gcd(self.num, self.den)
  1003. if div > 1:
  1004. self.num = self.num / div
  1005. self.den = self.den / div
  1006. # for ease of dealing with tags
  1007. class IFD_Tag:
  1008. def __init__(self, printable, tag, field_type, values, field_offset, field_length):
  1009. # printable version of data
  1010. self.printable = printable
  1011. # tag ID number
  1012. self.tag = tag
  1013. # field type as index into FIELD_TYPES
  1014. self.field_type = field_type
  1015. # offset of start of field in bytes from beginning of IFD
  1016. self.field_offset = field_offset
  1017. # length of data field in bytes
  1018. self.field_length = field_length
  1019. # either a string or array of data items
  1020. self.values = values
  1021. def __str__(self):
  1022. return self.printable
  1023. def __repr__(self):
  1024. return "(0x%04X) %s=%s @ %d" % (
  1025. self.tag,
  1026. FIELD_TYPES[self.field_type][2],
  1027. self.printable,
  1028. self.field_offset,
  1029. )
  1030. # class that handles an EXIF header
  1031. class EXIF_header:
  1032. def __init__(self, file, endian, offset, fake_exif, debug=0):
  1033. self.file = file
  1034. self.endian = endian
  1035. self.offset = offset
  1036. self.fake_exif = fake_exif
  1037. self.debug = debug
  1038. self.tags = {}
  1039. # convert slice to integer, based on sign and endian flags
  1040. # usually this offset is assumed to be relative to the beginning of the
  1041. # start of the EXIF information. For some cameras that use relative tags,
  1042. # this offset may be relative to some other starting point.
  1043. def s2n(self, offset, length, signed=0):
  1044. self.file.seek(self.offset + offset)
  1045. slice = self.file.read(length)
  1046. if self.endian == "I":
  1047. val = s2n_intel(slice)
  1048. else:
  1049. val = s2n_motorola(slice)
  1050. # Sign extension ?
  1051. if signed:
  1052. msb = 1L << (8 * length - 1)
  1053. if val & msb:
  1054. val = val - (msb << 1)
  1055. return val
  1056. # convert offset to string
  1057. def n2s(self, offset, length):
  1058. s = ""
  1059. for dummy in range(length):
  1060. if self.endian == "I":
  1061. s = s + chr(offset & 0xFF)
  1062. else:
  1063. s = chr(offset & 0xFF) + s
  1064. offset = offset >> 8
  1065. return s
  1066. # return first IFD
  1067. def first_IFD(self):
  1068. return self.s2n(4, 4)
  1069. # return pointer to next IFD
  1070. def next_IFD(self, ifd):
  1071. entries = self.s2n(ifd, 2)
  1072. return self.s2n(ifd + 2 + 12 * entries, 4)
  1073. # return list of IFDs in header
  1074. def list_IFDs(self):
  1075. i = self.first_IFD()
  1076. a = []
  1077. while i:
  1078. a.append(i)
  1079. i = self.next_IFD(i)
  1080. return a
  1081. # return list of entries in this IFD
  1082. def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0, stop_tag="UNDEF"):
  1083. entries = self.s2n(ifd, 2)
  1084. for i in range(entries):
  1085. # entry is index of start of this IFD in the file
  1086. entry = ifd + 2 + 12 * i
  1087. tag = self.s2n(entry, 2)
  1088. # get tag name early to avoid errors, help debug
  1089. tag_entry = dict.get(tag)
  1090. if tag_entry:
  1091. tag_name = tag_entry[0]
  1092. else:
  1093. tag_name = "Tag 0x%04X" % tag
  1094. # ignore certain tags for faster processing
  1095. if not (not detailed and tag in IGNORE_TAGS):
  1096. field_type = self.s2n(entry + 2, 2)
  1097. if not 0 < field_type < len(FIELD_TYPES):
  1098. # unknown field type
  1099. raise ValueError(
  1100. "unknown type %d in tag 0x%04X" % (field_type, tag)
  1101. )
  1102. typelen = FIELD_TYPES[field_type][0]
  1103. count = self.s2n(entry + 4, 4)
  1104. offset = entry + 8
  1105. if count * typelen > 4:
  1106. # offset is not the value; it's a pointer to the value
  1107. # if relative we set things up so s2n will seek to the right
  1108. # place when it adds self.offset. Note that this 'relative'
  1109. # is for the Nikon type 3 makernote. Other cameras may use
  1110. # other relative offsets, which would have to be computed here
  1111. # slightly differently.
  1112. if relative:
  1113. tmp_offset = self.s2n(offset, 4)
  1114. offset = tmp_offset + ifd - self.offset + 4
  1115. if self.fake_exif:
  1116. offset = offset + 18
  1117. else:
  1118. offset = self.s2n(offset, 4)
  1119. field_offset = offset
  1120. if field_type == 2:
  1121. # special case: null-terminated ASCII string
  1122. if count != 0:
  1123. self.file.seek(self.offset + offset)
  1124. values = self.file.read(count)
  1125. values = values.strip().replace("\x00", "")
  1126. else:
  1127. values = ""
  1128. else:
  1129. values = []
  1130. signed = field_type in [6, 8, 9, 10]
  1131. for dummy in range(count):
  1132. if field_type in (5, 10):
  1133. # a ratio
  1134. value = Ratio(
  1135. self.s2n(offset, 4, signed),
  1136. self.s2n(offset + 4, 4, signed),
  1137. )
  1138. else:
  1139. value = self.s2n(offset, typelen, signed)
  1140. values.append(value)
  1141. offset = offset + typelen
  1142. # now "values" is either a string or an array
  1143. if count == 1 and field_type != 2:
  1144. printable = str(values[0])
  1145. else:
  1146. printable = str(values)
  1147. # compute printable version of values
  1148. if tag_entry:
  1149. if len(tag_entry) != 1:
  1150. # optional 2nd tag element is present
  1151. if callable(tag_entry[1]):
  1152. # call mapping function
  1153. printable = tag_entry[1](values)
  1154. else:
  1155. printable = ""
  1156. for i in values:
  1157. # use lookup table for this tag
  1158. printable += tag_entry[1].get(i, repr(i))
  1159. self.tags[ifd_name + " " + tag_name] = IFD_Tag(
  1160. printable, tag, field_type, values, field_offset, count * typelen
  1161. )
  1162. if self.debug:
  1163. print " debug: %s: %s" % (
  1164. tag_name,
  1165. repr(self.tags[ifd_name + " " + tag_name]),
  1166. )
  1167. if tag_name == stop_tag:
  1168. break
  1169. # extract uncompressed TIFF thumbnail (like pulling teeth)
  1170. # we take advantage of the pre-existing layout in the thumbnail IFD as
  1171. # much as possible
  1172. def extract_TIFF_thumbnail(self, thumb_ifd):
  1173. entries = self.s2n(thumb_ifd, 2)
  1174. # this is header plus offset to IFD ...
  1175. if self.endian == "M":
  1176. tiff = "MM\x00*\x00\x00\x00\x08"
  1177. else:
  1178. tiff = "II*\x00\x08\x00\x00\x00"
  1179. # ... plus thumbnail IFD data plus a null "next IFD" pointer
  1180. self.file.seek(self.offset + thumb_ifd)
  1181. tiff += self.file.read(entries * 12 + 2) + "\x00\x00\x00\x00"
  1182. # fix up large value offset pointers into data area
  1183. for i in range(entries):
  1184. entry = thumb_ifd + 2 + 12 * i
  1185. tag = self.s2n(entry, 2)
  1186. field_type = self.s2n(entry + 2, 2)
  1187. typelen = FIELD_TYPES[field_type][0]
  1188. count = self.s2n(entry + 4, 4)
  1189. oldoff = self.s2n(entry + 8, 4)
  1190. # start of the 4-byte pointer area in entry
  1191. ptr = i * 12 + 18
  1192. # remember strip offsets location
  1193. if tag == 0x0111:
  1194. strip_off = ptr
  1195. strip_len = count * typelen
  1196. # is it in the data area?
  1197. if count * typelen > 4:
  1198. # update offset pointer (nasty "strings are immutable" crap)
  1199. # should be able to say "tiff[ptr:ptr+4]=newoff"
  1200. newoff = len(tiff)
  1201. tiff = tiff[:ptr] + self.n2s(newoff, 4) + tiff[ptr + 4 :]
  1202. # remember strip offsets location
  1203. if tag == 0x0111:
  1204. strip_off = newoff
  1205. strip_len = 4
  1206. # get original data and store it
  1207. self.file.seek(self.offset + oldoff)
  1208. tiff += self.file.read(count * typelen)
  1209. # add pixel strips and update strip offset info
  1210. old_offsets = self.tags["Thumbnail StripOffsets"].values
  1211. old_counts = self.tags["Thumbnail StripByteCounts"].values
  1212. for i in range(len(old_offsets)):
  1213. # update offset pointer (more nasty "strings are immutable" crap)
  1214. offset = self.n2s(len(tiff), strip_len)
  1215. tiff = tiff[:strip_off] + offset + tiff[strip_off + strip_len :]
  1216. strip_off += strip_len
  1217. # add pixel strip to end
  1218. self.file.seek(self.offset + old_offsets[i])
  1219. tiff += self.file.read(old_counts[i])
  1220. self.tags["TIFFThumbnail"] = tiff
  1221. # decode all the camera-specific MakerNote formats
  1222. # Note is the data that comprises this MakerNote. The MakerNote will
  1223. # likely have pointers in it that point to other parts of the file. We'll
  1224. # use self.offset as the starting point for most of those pointers, since
  1225. # they are relative to the beginning of the file.
  1226. #
  1227. # If the MakerNote is in a newer format, it may use relative addressing
  1228. # within the MakerNote. In that case we'll use relative addresses for the
  1229. # pointers.
  1230. #
  1231. # As an aside: it's not just to be annoying that the manufacturers use
  1232. # relative offsets. It's so that if the makernote has to be moved by the
  1233. # picture software all of the offsets don't have to be adjusted. Overall,
  1234. # this is probably the right strategy for makernotes, though the spec is
  1235. # ambiguous. (The spec does not appear to imagine that makernotes would
  1236. # follow EXIF format internally. Once they did, it's ambiguous whether
  1237. # the offsets should be from the header at the start of all the EXIF info,
  1238. # or from the header at the start of the makernote.)
  1239. def decode_maker_note(self):
  1240. note = self.tags["EXIF MakerNote"]
  1241. make = self.tags["Image Make"].printable
  1242. # model = self.tags['Image Model'].printable # unused
  1243. # Nikon
  1244. # The maker note usually starts with the word Nikon, followed by the
  1245. # type of the makernote (1 or 2, as a short). If the word Nikon is
  1246. # not at the start of the makernote, it's probably type 2, since some
  1247. # cameras work that way.
  1248. if make in ("NIKON", "NIKON CORPORATION"):
  1249. if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]:
  1250. if self.debug:
  1251. print "Looks like a type 1 Nikon MakerNote."
  1252. self.dump_IFD(
  1253. note.field_offset + 8, "MakerNote", dict=MAKERNOTE_NIKON_OLDER_TAGS
  1254. )
  1255. elif note.values[0:7] == [78, 105, 107, 111, 110, 0, 2]:
  1256. if self.debug:
  1257. print "Looks like a labeled type 2 Nikon MakerNote"
  1258. if note.values[12:14] != [0, 42] and note.values[12:14] != [42L, 0L]:
  1259. raise ValueError("Missing marker tag '42' in MakerNote.")
  1260. # skip the Makernote label and the TIFF header
  1261. self.dump_IFD(
  1262. note.field_offset + 10 + 8,
  1263. "MakerNote",
  1264. dict=MAKERNOTE_NIKON_NEWER_TAGS,
  1265. relative=1,
  1266. )
  1267. else:
  1268. # E99x or D1
  1269. if self.debug:
  1270. print "Looks like an unlabeled type 2 Nikon MakerNote"
  1271. self.dump_IFD(
  1272. note.field_offset, "MakerNote", dict=MAKERNOTE_NIKON_NEWER_TAGS
  1273. )
  1274. return
  1275. # Olympus
  1276. if make.startswith("OLYMPUS"):
  1277. self.dump_IFD(
  1278. note.field_offset + 8, "MakerNote", dict=MAKERNOTE_OLYMPUS_TAGS
  1279. )
  1280. # TODO
  1281. # for i in (('MakerNote Tag 0x2020', MAKERNOTE_OLYMPUS_TAG_0x2020),):
  1282. # self.decode_olympus_tag(self.tags[i[0]].values, i[1])
  1283. # return
  1284. # Casio
  1285. if make == "Casio":
  1286. self.dump_IFD(note.field_offset, "MakerNote", dict=MAKERNOTE_CASIO_TAGS)
  1287. return
  1288. # Fujifilm
  1289. if make == "FUJIFILM":
  1290. # bug: everything else is "Motorola" endian, but the MakerNote
  1291. # is "Intel" endian
  1292. endian = self.endian
  1293. self.endian = "I"
  1294. # bug: IFD offsets are from beginning of MakerNote, not
  1295. # beginning of file header
  1296. offset = self.offset
  1297. self.offset += note.field_offset
  1298. # process note with bogus values (note is actually at offset 12)
  1299. self.dump_IFD(12, "MakerNote", dict=MAKERNOTE_FUJIFILM_TAGS)
  1300. # reset to correct values
  1301. self.endian = endian
  1302. self.offset = offset
  1303. return
  1304. # Canon
  1305. if make == "Canon":
  1306. self.dump_IFD(note.field_offset, "MakerNote", dict=MAKERNOTE_CANON_TAGS)
  1307. for i in (
  1308. ("MakerNote Tag 0x0001", MAKERNOTE_CANON_TAG_0x001),
  1309. ("MakerNote Tag 0x0004", MAKERNOTE_CANON_TAG_0x004),
  1310. ):
  1311. self.canon_decode_tag(self.tags[i[0]].values, i[1])
  1312. return
  1313. # decode Olympus MakerNote tag based on offset within tag
  1314. def olympus_decode_tag(self, value, dict):
  1315. pass
  1316. # decode Canon MakerNote tag based on offset within tag
  1317. # see http://www.burren.cx/david/canon.html by David Burren
  1318. def canon_decode_tag(self, value, dict):
  1319. for i in range(1, len(value)):
  1320. x = dict.get(i, ("Unknown",))
  1321. if self.debug:
  1322. print i, x
  1323. name = x[0]
  1324. if len(x) > 1:
  1325. val = x[1].get(value[i], "Unknown")
  1326. else:
  1327. val = value[i]
  1328. # it's not a real IFD Tag but we fake one to make everybody
  1329. # happy. this will have a "proprietary" type
  1330. self.tags["MakerNote " + name] = IFD_Tag(
  1331. str(val), None, 0, None, None, None
  1332. )
  1333. # process an image file (expects an open file object)
  1334. # this is the function that has to deal with all the arbitrary nasty bits
  1335. # of the EXIF standard
  1336. def process_file(f, stop_tag="UNDEF", details=True, debug=False):
  1337. # yah it's cheesy...
  1338. global detailed
  1339. detailed = details
  1340. # by default do not fake an EXIF beginning
  1341. fake_exif = 0
  1342. # determine whether it's a JPEG or TIFF
  1343. data = f.read(12)
  1344. if data[0:4] in ["II*\x00", "MM\x00*"]:
  1345. # it's a TIFF file
  1346. f.seek(0)
  1347. endian = f.read(1)
  1348. f.read(1)
  1349. offset = 0
  1350. elif data[0:2] == "\xFF\xD8":
  1351. # it's a JPEG file
  1352. while data[2] == "\xFF" and data[6:10] in ("JFIF", "JFXX", "OLYM", "Phot"):
  1353. length = ord(data[4]) * 256 + ord(data[5])
  1354. f.read(length - 8)
  1355. # fake an EXIF beginning of file
  1356. data = "\xFF\x00" + f.read(10)
  1357. fake_exif = 1
  1358. if data[2] == "\xFF" and data[6:10] == "Exif":
  1359. # detected EXIF header
  1360. offset = f.tell()
  1361. endian = f.read(1)
  1362. else:
  1363. # no EXIF information
  1364. return {}
  1365. else:
  1366. # file format not recognized
  1367. return {}
  1368. # deal with the EXIF info we found
  1369. if debug:
  1370. print {"I": "Intel", "M": "Motorola"}[endian], "format"
  1371. hdr = EXIF_header(f, endian, offset, fake_exif, debug)
  1372. ifd_list = hdr.list_IFDs()
  1373. ctr = 0
  1374. for i in ifd_list:
  1375. if ctr == 0:
  1376. IFD_name = "Image"
  1377. elif ctr == 1:
  1378. IFD_name = "Thumbnail"
  1379. thumb_ifd = i
  1380. else:
  1381. IFD_name = "IFD %d" % ctr
  1382. if debug:
  1383. print " IFD %d (%s) at offset %d:" % (ctr, IFD_name, i)
  1384. hdr.dump_IFD(i, IFD_name, stop_tag=stop_tag)
  1385. # EXIF IFD
  1386. exif_off = hdr.tags.get(IFD_name + " ExifOffset")
  1387. if exif_off:
  1388. if debug:
  1389. print " EXIF SubIFD at offset %d:" % exif_off.values[0]
  1390. hdr.dump_IFD(exif_off.values[0], "EXIF", stop_tag=stop_tag)
  1391. # Interoperability IFD contained in EXIF IFD
  1392. intr_off = hdr.tags.get("EXIF SubIFD InteroperabilityOffset")
  1393. if intr_off:
  1394. if debug:
  1395. print " EXIF Interoperability SubSubIFD at offset %d:" % intr_off.values[
  1396. 0
  1397. ]
  1398. hdr.dump_IFD(
  1399. intr_off.values[0],
  1400. "EXIF Interoperability",
  1401. dict=INTR_TAGS,
  1402. stop_tag=stop_tag,
  1403. )
  1404. # GPS IFD
  1405. gps_off = hdr.tags.get(IFD_name + " GPSInfo")
  1406. if gps_off:
  1407. if debug:
  1408. print " GPS SubIFD at offset %d:" % gps_off.values[0]
  1409. hdr.dump_IFD(gps_off.values[0], "GPS", dict=GPS_TAGS, stop_tag=stop_tag)
  1410. ctr += 1
  1411. # extract uncompressed TIFF thumbnail
  1412. thumb = hdr.tags.get("Thumbnail Compression")
  1413. if thumb and thumb.printable == "Uncompressed TIFF":
  1414. hdr.extract_TIFF_thumbnail(thumb_ifd)
  1415. # JPEG thumbnail (thankfully the JPEG data is stored as a unit)
  1416. thumb_off = hdr.tags.get("Thumbnail JPEGInterchangeFormat")
  1417. if thumb_off:
  1418. f.seek(offset + thumb_off.values[0])
  1419. size = hdr.tags["Thumbnail JPEGInterchangeFormatLength"].values[0]
  1420. hdr.tags["JPEGThumbnail"] = f.read(size)
  1421. # deal with MakerNote contained in EXIF IFD
  1422. if "EXIF MakerNote" in hdr.tags and detailed:
  1423. hdr.decode_maker_note()
  1424. # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote
  1425. # since it's not allowed in a uncompressed TIFF IFD
  1426. if "JPEGThumbnail" not in hdr.tags:
  1427. thumb_off = hdr.tags.get("MakerNote JPEGThumbnail")
  1428. if thumb_off:
  1429. f.seek(offset + thumb_off.values[0])
  1430. hdr.tags["JPEGThumbnail"] = file.read(thumb_off.field_length)
  1431. return hdr.tags
  1432. # show command line usage
  1433. def usage(exit_status):
  1434. msg = "Usage: EXIF.py [OPTIONS] file1 [file2 ...]\n"
  1435. msg += "Extract EXIF information from digital camera image files.\n\nOptions:\n"
  1436. msg += "-q --quick Do not process MakerNotes.\n"
  1437. msg += "-t TAG --stop-tag TAG Stop processing when this tag is retrieved.\n"
  1438. msg += "-d --debug Run in debug mode.\n"
  1439. print msg
  1440. sys.exit(exit_status)
  1441. # library test/debug function (dump given files)
  1442. if __name__ == "__main__":
  1443. import sys
  1444. import getopt
  1445. # parse command line options/arguments
  1446. try:
  1447. opts, args = getopt.getopt(
  1448. sys.argv[1:], "hqdt:v", ["help", "quick", "debug", "stop-tag="]
  1449. )
  1450. except getopt.GetoptError:
  1451. usage(2)
  1452. if args == []:
  1453. usage(2)
  1454. detailed = True
  1455. stop_tag = "UNDEF"
  1456. debug = False
  1457. for o, a in opts:
  1458. if o in ("-h", "--help"):
  1459. usage(0)
  1460. if o in ("-q", "--quick"):
  1461. detailed = False
  1462. if o in ("-t", "--stop-tag"):
  1463. stop_tag = a
  1464. if o in ("-d", "--debug"):
  1465. debug = True
  1466. # output info for each file
  1467. for filename in args:
  1468. try:
  1469. file = open(filename, "rb")
  1470. except:
  1471. print "'%s' is unreadable\n" % filename
  1472. continue
  1473. print filename + ":"
  1474. # get the tags
  1475. data = process_file(file, stop_tag=stop_tag, details=detailed, debug=debug)
  1476. if not data:
  1477. print "No EXIF information found"
  1478. continue
  1479. x = data.keys()
  1480. x.sort()
  1481. for i in x:
  1482. if i in ("JPEGThumbnail", "TIFFThumbnail"):
  1483. continue
  1484. try:
  1485. print " %s (%s): %s" % (
  1486. i,
  1487. FIELD_TYPES[data[i].field_type][2],
  1488. data[i].printable,
  1489. )
  1490. except:
  1491. print "error", i, '"', data[i], '"'
  1492. if "JPEGThumbnail" in data:
  1493. print "File has JPEG thumbnail"
  1494. print