EXIF.py 52 KB

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