vue.ts 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. // @ts-nocheck
  2. import { base64ToArrayBuffer } from '../base64ToArrayBuffer';
  3. import { pathToBase64 } from '../pathToBase64';
  4. // import { isBase64 } from '../isBase64';
  5. import { isBase64DataUri } from '../isBase64';
  6. import { isString } from '../isString';
  7. interface File {
  8. exifdata : any
  9. iptcdata : any
  10. xmpdata : any
  11. src : string
  12. }
  13. class EXIF {
  14. isXmpEnabled = false
  15. debug = false
  16. Tags = {
  17. // version tags
  18. 0x9000: "ExifVersion", // EXIF version
  19. 0xA000: "FlashpixVersion", // Flashpix format version
  20. // colorspace tags
  21. 0xA001: "ColorSpace", // Color space information tag
  22. // image configuration
  23. 0xA002: "PixelXDimension", // Valid width of meaningful image
  24. 0xA003: "PixelYDimension", // Valid height of meaningful image
  25. 0x9101: "ComponentsConfiguration", // Information about channels
  26. 0x9102: "CompressedBitsPerPixel", // Compressed bits per pixel
  27. // user information
  28. 0x927C: "MakerNote", // Any desired information written by the manufacturer
  29. 0x9286: "UserComment", // Comments by user
  30. // related file
  31. 0xA004: "RelatedSoundFile", // Name of related sound file
  32. // date and time
  33. 0x9003: "DateTimeOriginal", // Date and time when the original image was generated
  34. 0x9004: "DateTimeDigitized", // Date and time when the image was stored digitally
  35. 0x9290: "SubsecTime", // Fractions of seconds for DateTime
  36. 0x9291: "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
  37. 0x9292: "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
  38. // picture-taking conditions
  39. 0x829A: "ExposureTime", // Exposure time (in seconds)
  40. 0x829D: "FNumber", // F number
  41. 0x8822: "ExposureProgram", // Exposure program
  42. 0x8824: "SpectralSensitivity", // Spectral sensitivity
  43. 0x8827: "ISOSpeedRatings", // ISO speed rating
  44. 0x8828: "OECF", // Optoelectric conversion factor
  45. 0x9201: "ShutterSpeedValue", // Shutter speed
  46. 0x9202: "ApertureValue", // Lens aperture
  47. 0x9203: "BrightnessValue", // Value of brightness
  48. 0x9204: "ExposureBias", // Exposure bias
  49. 0x9205: "MaxApertureValue", // Smallest F number of lens
  50. 0x9206: "SubjectDistance", // Distance to subject in meters
  51. 0x9207: "MeteringMode", // Metering mode
  52. 0x9208: "LightSource", // Kind of light source
  53. 0x9209: "Flash", // Flash status
  54. 0x9214: "SubjectArea", // Location and area of main subject
  55. 0x920A: "FocalLength", // Focal length of the lens in mm
  56. 0xA20B: "FlashEnergy", // Strobe energy in BCPS
  57. 0xA20C: "SpatialFrequencyResponse", //
  58. 0xA20E: "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
  59. 0xA20F: "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
  60. 0xA210: "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
  61. 0xA214: "SubjectLocation", // Location of subject in image
  62. 0xA215: "ExposureIndex", // Exposure index selected on camera
  63. 0xA217: "SensingMethod", // Image sensor type
  64. 0xA300: "FileSource", // Image source (3 == DSC)
  65. 0xA301: "SceneType", // Scene type (1 == directly photographed)
  66. 0xA302: "CFAPattern", // Color filter array geometric pattern
  67. 0xA401: "CustomRendered", // Special processing
  68. 0xA402: "ExposureMode", // Exposure mode
  69. 0xA403: "WhiteBalance", // 1 = auto white balance, 2 = manual
  70. 0xA404: "DigitalZoomRation", // Digital zoom ratio
  71. 0xA405: "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
  72. 0xA406: "SceneCaptureType", // Type of scene
  73. 0xA407: "GainControl", // Degree of overall image gain adjustment
  74. 0xA408: "Contrast", // Direction of contrast processing applied by camera
  75. 0xA409: "Saturation", // Direction of saturation processing applied by camera
  76. 0xA40A: "Sharpness", // Direction of sharpness processing applied by camera
  77. 0xA40B: "DeviceSettingDescription", //
  78. 0xA40C: "SubjectDistanceRange", // Distance to subject
  79. // other tags
  80. 0xA005: "InteroperabilityIFDPointer",
  81. 0xA420: "ImageUniqueID" // Identifier assigned uniquely to each image
  82. }
  83. TiffTags = {
  84. 0x0100: "ImageWidth",
  85. 0x0101: "ImageHeight",
  86. 0x8769: "ExifIFDPointer",
  87. 0x8825: "GPSInfoIFDPointer",
  88. 0xA005: "InteroperabilityIFDPointer",
  89. 0x0102: "BitsPerSample",
  90. 0x0103: "Compression",
  91. 0x0106: "PhotometricInterpretation",
  92. 0x0112: "Orientation",
  93. 0x0115: "SamplesPerPixel",
  94. 0x011C: "PlanarConfiguration",
  95. 0x0212: "YCbCrSubSampling",
  96. 0x0213: "YCbCrPositioning",
  97. 0x011A: "XResolution",
  98. 0x011B: "YResolution",
  99. 0x0128: "ResolutionUnit",
  100. 0x0111: "StripOffsets",
  101. 0x0116: "RowsPerStrip",
  102. 0x0117: "StripByteCounts",
  103. 0x0201: "JPEGInterchangeFormat",
  104. 0x0202: "JPEGInterchangeFormatLength",
  105. 0x012D: "TransferFunction",
  106. 0x013E: "WhitePoint",
  107. 0x013F: "PrimaryChromaticities",
  108. 0x0211: "YCbCrCoefficients",
  109. 0x0214: "ReferenceBlackWhite",
  110. 0x0132: "DateTime",
  111. 0x010E: "ImageDescription",
  112. 0x010F: "Make",
  113. 0x0110: "Model",
  114. 0x0131: "Software",
  115. 0x013B: "Artist",
  116. 0x8298: "Copyright"
  117. }
  118. GPSTags = {
  119. 0x0000: "GPSVersionID",
  120. 0x0001: "GPSLatitudeRef",
  121. 0x0002: "GPSLatitude",
  122. 0x0003: "GPSLongitudeRef",
  123. 0x0004: "GPSLongitude",
  124. 0x0005: "GPSAltitudeRef",
  125. 0x0006: "GPSAltitude",
  126. 0x0007: "GPSTimeStamp",
  127. 0x0008: "GPSSatellites",
  128. 0x0009: "GPSStatus",
  129. 0x000A: "GPSMeasureMode",
  130. 0x000B: "GPSDOP",
  131. 0x000C: "GPSSpeedRef",
  132. 0x000D: "GPSSpeed",
  133. 0x000E: "GPSTrackRef",
  134. 0x000F: "GPSTrack",
  135. 0x0010: "GPSImgDirectionRef",
  136. 0x0011: "GPSImgDirection",
  137. 0x0012: "GPSMapDatum",
  138. 0x0013: "GPSDestLatitudeRef",
  139. 0x0014: "GPSDestLatitude",
  140. 0x0015: "GPSDestLongitudeRef",
  141. 0x0016: "GPSDestLongitude",
  142. 0x0017: "GPSDestBearingRef",
  143. 0x0018: "GPSDestBearing",
  144. 0x0019: "GPSDestDistanceRef",
  145. 0x001A: "GPSDestDistance",
  146. 0x001B: "GPSProcessingMethod",
  147. 0x001C: "GPSAreaInformation",
  148. 0x001D: "GPSDateStamp",
  149. 0x001E: "GPSDifferential"
  150. }
  151. // EXIF 2.3 Spec
  152. IFD1Tags = {
  153. 0x0100: "ImageWidth",
  154. 0x0101: "ImageHeight",
  155. 0x0102: "BitsPerSample",
  156. 0x0103: "Compression",
  157. 0x0106: "PhotometricInterpretation",
  158. 0x0111: "StripOffsets",
  159. 0x0112: "Orientation",
  160. 0x0115: "SamplesPerPixel",
  161. 0x0116: "RowsPerStrip",
  162. 0x0117: "StripByteCounts",
  163. 0x011A: "XResolution",
  164. 0x011B: "YResolution",
  165. 0x011C: "PlanarConfiguration",
  166. 0x0128: "ResolutionUnit",
  167. 0x0201: "JpegIFOffset", // When image format is JPEG, this value show offset to JPEG data stored.(aka "ThumbnailOffset" or "JPEGInterchangeFormat")
  168. 0x0202: "JpegIFByteCount", // When image format is JPEG, this value shows data size of JPEG image (aka "ThumbnailLength" or "JPEGInterchangeFormatLength")
  169. 0x0211: "YCbCrCoefficients",
  170. 0x0212: "YCbCrSubSampling",
  171. 0x0213: "YCbCrPositioning",
  172. 0x0214: "ReferenceBlackWhite"
  173. }
  174. StringValues = {
  175. ExposureProgram: {
  176. 0: "Not defined",
  177. 1: "Manual",
  178. 2: "Normal program",
  179. 3: "Aperture priority",
  180. 4: "Shutter priority",
  181. 5: "Creative program",
  182. 6: "Action program",
  183. 7: "Portrait mode",
  184. 8: "Landscape mode"
  185. },
  186. MeteringMode: {
  187. 0: "Unknown",
  188. 1: "Average",
  189. 2: "CenterWeightedAverage",
  190. 3: "Spot",
  191. 4: "MultiSpot",
  192. 5: "Pattern",
  193. 6: "Partial",
  194. 255: "Other"
  195. },
  196. LightSource: {
  197. 0: "Unknown",
  198. 1: "Daylight",
  199. 2: "Fluorescent",
  200. 3: "Tungsten (incandescent light)",
  201. 4: "Flash",
  202. 9: "Fine weather",
  203. 10: "Cloudy weather",
  204. 11: "Shade",
  205. 12: "Daylight fluorescent (D 5700 - 7100K)",
  206. 13: "Day white fluorescent (N 4600 - 5400K)",
  207. 14: "Cool white fluorescent (W 3900 - 4500K)",
  208. 15: "White fluorescent (WW 3200 - 3700K)",
  209. 17: "Standard light A",
  210. 18: "Standard light B",
  211. 19: "Standard light C",
  212. 20: "D55",
  213. 21: "D65",
  214. 22: "D75",
  215. 23: "D50",
  216. 24: "ISO studio tungsten",
  217. 255: "Other"
  218. },
  219. Flash: {
  220. 0x0000: "Flash did not fire",
  221. 0x0001: "Flash fired",
  222. 0x0005: "Strobe return light not detected",
  223. 0x0007: "Strobe return light detected",
  224. 0x0009: "Flash fired, compulsory flash mode",
  225. 0x000D: "Flash fired, compulsory flash mode, return light not detected",
  226. 0x000F: "Flash fired, compulsory flash mode, return light detected",
  227. 0x0010: "Flash did not fire, compulsory flash mode",
  228. 0x0018: "Flash did not fire, auto mode",
  229. 0x0019: "Flash fired, auto mode",
  230. 0x001D: "Flash fired, auto mode, return light not detected",
  231. 0x001F: "Flash fired, auto mode, return light detected",
  232. 0x0020: "No flash function",
  233. 0x0041: "Flash fired, red-eye reduction mode",
  234. 0x0045: "Flash fired, red-eye reduction mode, return light not detected",
  235. 0x0047: "Flash fired, red-eye reduction mode, return light detected",
  236. 0x0049: "Flash fired, compulsory flash mode, red-eye reduction mode",
  237. 0x004D: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
  238. 0x004F: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
  239. 0x0059: "Flash fired, auto mode, red-eye reduction mode",
  240. 0x005D: "Flash fired, auto mode, return light not detected, red-eye reduction mode",
  241. 0x005F: "Flash fired, auto mode, return light detected, red-eye reduction mode"
  242. },
  243. SensingMethod: {
  244. 1: "Not defined",
  245. 2: "One-chip color area sensor",
  246. 3: "Two-chip color area sensor",
  247. 4: "Three-chip color area sensor",
  248. 5: "Color sequential area sensor",
  249. 7: "Trilinear sensor",
  250. 8: "Color sequential linear sensor"
  251. },
  252. SceneCaptureType: {
  253. 0: "Standard",
  254. 1: "Landscape",
  255. 2: "Portrait",
  256. 3: "Night scene"
  257. },
  258. SceneType: {
  259. 1: "Directly photographed"
  260. },
  261. CustomRendered: {
  262. 0: "Normal process",
  263. 1: "Custom process"
  264. },
  265. WhiteBalance: {
  266. 0: "Auto white balance",
  267. 1: "Manual white balance"
  268. },
  269. GainControl: {
  270. 0: "None",
  271. 1: "Low gain up",
  272. 2: "High gain up",
  273. 3: "Low gain down",
  274. 4: "High gain down"
  275. },
  276. Contrast: {
  277. 0: "Normal",
  278. 1: "Soft",
  279. 2: "Hard"
  280. },
  281. Saturation: {
  282. 0: "Normal",
  283. 1: "Low saturation",
  284. 2: "High saturation"
  285. },
  286. Sharpness: {
  287. 0: "Normal",
  288. 1: "Soft",
  289. 2: "Hard"
  290. },
  291. SubjectDistanceRange: {
  292. 0: "Unknown",
  293. 1: "Macro",
  294. 2: "Close view",
  295. 3: "Distant view"
  296. },
  297. FileSource: {
  298. 3: "DSC"
  299. },
  300. Components: {
  301. 0: "",
  302. 1: "Y",
  303. 2: "Cb",
  304. 3: "Cr",
  305. 4: "R",
  306. 5: "G",
  307. 6: "B"
  308. }
  309. }
  310. enableXmp() {
  311. this.isXmpEnabled = true
  312. }
  313. disableXmp() {
  314. this.isXmpEnabled = false;
  315. }
  316. /**
  317. * 获取图片数据
  318. * @param img 图片地址
  319. * @param callback 回调 返回图片数据
  320. * */
  321. getData(img : any, callback : Function) {
  322. // if (((self.Image && img instanceof self.Image) || (self.HTMLImageElement && img instanceof self.HTMLImageElement)) && !img.complete)
  323. // return false;
  324. let file : File = {
  325. src: '',
  326. exifdata: null,
  327. iptcdata: null,
  328. xmpdata: null,
  329. }
  330. if (isBase64(img)) {
  331. file.src = img
  332. } else if (img.path) {
  333. file.src = img.path
  334. } else if (isString(img)) {
  335. file.src = img
  336. } else {
  337. return false;
  338. }
  339. if (!imageHasData(file)) {
  340. getImageData(file, callback);
  341. } else {
  342. if (callback) {
  343. callback.call(file);
  344. }
  345. }
  346. return true;
  347. }
  348. /**
  349. * 获取图片tag
  350. * @param img 图片数据
  351. * @param tag tag 类型
  352. * */
  353. getTag(img : File, tag : string) {
  354. if (!imageHasData(img)) return;
  355. return img.exifdata[tag];
  356. }
  357. getIptcTag(img : File, tag : string) {
  358. if (!imageHasData(img)) return;
  359. return img.iptcdata[tag];
  360. }
  361. getAllTags(img : File) {
  362. if (!imageHasData(img)) return {};
  363. let a,
  364. data = img.exifdata,
  365. tags = {};
  366. for (a in data) {
  367. if (data.hasOwnProperty(a)) {
  368. tags[a] = data[a];
  369. }
  370. }
  371. return tags;
  372. }
  373. getAllIptcTags(img : File) {
  374. if (!imageHasData(img)) return {};
  375. let a,
  376. data = img.iptcdata,
  377. tags = {};
  378. for (a in data) {
  379. if (data.hasOwnProperty(a)) {
  380. tags[a] = data[a];
  381. }
  382. }
  383. return tags;
  384. }
  385. pretty(img : File) {
  386. if (!imageHasData(img)) return "";
  387. let a,
  388. data = img.exifdata,
  389. strPretty = "";
  390. for (a in data) {
  391. if (data.hasOwnProperty(a)) {
  392. if (typeof data[a] == "object") {
  393. if (data[a] instanceof Number) {
  394. strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a]
  395. .denominator + "]\r\n";
  396. } else {
  397. strPretty += a + " : [" + data[a].length + " values]\r\n";
  398. }
  399. } else {
  400. strPretty += a + " : " + data[a] + "\r\n";
  401. }
  402. }
  403. }
  404. return strPretty;
  405. }
  406. readFromBinaryFile(file: ArrayBuffer) {
  407. return findEXIFinJPEG(file);
  408. }
  409. }
  410. export const exif = new EXIF()
  411. // export function getData(img, callback) {
  412. // const exif = new EXIF()
  413. // exif.getData(img, callback)
  414. // }
  415. // export default {getData}
  416. const ExifTags = exif.Tags
  417. const TiffTags = exif.TiffTags
  418. const IFD1Tags = exif.IFD1Tags
  419. const GPSTags = exif.GPSTags
  420. const StringValues = exif.StringValues
  421. function imageHasData(img : File) : boolean {
  422. return !!(img.exifdata);
  423. }
  424. function objectURLToBlob(url : string, callback : Function) {
  425. try {
  426. const http = new XMLHttpRequest();
  427. http.open("GET", url, true);
  428. http.responseType = "blob";
  429. http.onload = function (e) {
  430. if (this.status == 200 || this.status === 0) {
  431. callback(this.response);
  432. }
  433. };
  434. http.send();
  435. } catch (e) {
  436. console.warn(e)
  437. }
  438. }
  439. function getImageData(img : File, callback : Function) {
  440. function handleBinaryFile(binFile: ArrayBuffer) {
  441. const data = findEXIFinJPEG(binFile);
  442. img.exifdata = data ?? {};
  443. const iptcdata = findIPTCinJPEG(binFile);
  444. img.iptcdata = iptcdata ?? {};
  445. if (exif.isXmpEnabled) {
  446. const xmpdata = findXMPinJPEG(binFile);
  447. img.xmpdata = xmpdata ?? {};
  448. }
  449. if (callback) {
  450. callback.call(img);
  451. }
  452. }
  453. if (img.src) {
  454. if (/^data\:/i.test(img.src)) { // Data URI
  455. // var arrayBuffer = base64ToArrayBuffer(img.src);
  456. handleBinaryFile(base64ToArrayBuffer(img.src));
  457. } else if (/^blob\:/i.test(img.src) && typeof FileReader !== 'undefined') { // Object URL
  458. var fileReader = new FileReader();
  459. fileReader.onload = function (e) {
  460. handleBinaryFile(e.target.result);
  461. };
  462. objectURLToBlob(img.src, function (blob : Blob) {
  463. fileReader.readAsArrayBuffer(blob);
  464. });
  465. } else if (typeof XMLHttpRequest !== 'undefined') {
  466. var http = new XMLHttpRequest();
  467. http.onload = function () {
  468. if (this.status == 200 || this.status === 0) {
  469. handleBinaryFile(http.response);
  470. } else {
  471. throw "Could not load image";
  472. }
  473. http = null;
  474. };
  475. http.open("GET", img.src, true);
  476. http.responseType = "arraybuffer";
  477. http.send(null);
  478. } else {
  479. pathToBase64(img.src).then(res => {
  480. handleBinaryFile(base64ToArrayBuffer(res));
  481. })
  482. }
  483. } else if (typeof FileReader !== 'undefined' && self.FileReader && (img instanceof self.Blob || img instanceof self.File)) {
  484. var fileReader = new FileReader();
  485. fileReader.onload = function (e : any) {
  486. if (exif.debug) console.log("Got file of length " + e.target.result.byteLength);
  487. handleBinaryFile(e.target.result);
  488. };
  489. fileReader.readAsArrayBuffer(img);
  490. }
  491. }
  492. function findEXIFinJPEG(file: ArrayBuffer) {
  493. const dataView = new DataView(file);
  494. if (exif.debug) console.log("Got file of length " + file.byteLength);
  495. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  496. if (exif.debug) console.log("Not a valid JPEG");
  497. return false; // not a valid jpeg
  498. }
  499. let offset = 2,
  500. length = file.byteLength,
  501. marker;
  502. while (offset < length) {
  503. if (dataView.getUint8(offset) != 0xFF) {
  504. if (exif.debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(
  505. offset));
  506. return false; // not a valid marker, something is wrong
  507. }
  508. marker = dataView.getUint8(offset + 1);
  509. if (exif.debug) console.log(marker);
  510. // we could implement handling for other markers here,
  511. // but we're only looking for 0xFFE1 for EXIF data
  512. if (marker == 225) {
  513. if (exif.debug) console.log("Found 0xFFE1 marker");
  514. return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
  515. // offset += 2 + file.getShortAt(offset+2, true);
  516. } else {
  517. offset += 2 + dataView.getUint16(offset + 2);
  518. }
  519. }
  520. }
  521. function findIPTCinJPEG(file: ArrayBuffer) {
  522. const dataView = new DataView(file);
  523. if (exif.debug) console.log("Got file of length " + file.byteLength);
  524. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  525. if (exif.debug) console.log("Not a valid JPEG");
  526. return false; // not a valid jpeg
  527. }
  528. let offset = 2,
  529. length = file.byteLength;
  530. const isFieldSegmentStart = function (dataView, offset: number) {
  531. return (
  532. dataView.getUint8(offset) === 0x38 &&
  533. dataView.getUint8(offset + 1) === 0x42 &&
  534. dataView.getUint8(offset + 2) === 0x49 &&
  535. dataView.getUint8(offset + 3) === 0x4D &&
  536. dataView.getUint8(offset + 4) === 0x04 &&
  537. dataView.getUint8(offset + 5) === 0x04
  538. );
  539. };
  540. while (offset < length) {
  541. if (isFieldSegmentStart(dataView, offset)) {
  542. // Get the length of the name header (which is padded to an even number of bytes)
  543. var nameHeaderLength = dataView.getUint8(offset + 7);
  544. if (nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
  545. // Check for pre photoshop 6 format
  546. if (nameHeaderLength === 0) {
  547. // Always 4
  548. nameHeaderLength = 4;
  549. }
  550. var startOffset = offset + 8 + nameHeaderLength;
  551. var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
  552. return readIPTCData(file, startOffset, sectionLength);
  553. break;
  554. }
  555. // Not the marker, continue searching
  556. offset++;
  557. }
  558. }
  559. const IptcFieldMap = {
  560. 0x78: 'caption',
  561. 0x6E: 'credit',
  562. 0x19: 'keywords',
  563. 0x37: 'dateCreated',
  564. 0x50: 'byline',
  565. 0x55: 'bylineTitle',
  566. 0x7A: 'captionWriter',
  567. 0x69: 'headline',
  568. 0x74: 'copyright',
  569. 0x0F: 'category'
  570. };
  571. function readIPTCData(file: ArrayBuffer, startOffset: number, sectionLength: number) {
  572. const dataView = new DataView(file);
  573. let data = {};
  574. let fieldValue, fieldName, dataSize, segmentType, segmentSize;
  575. let segmentStartPos = startOffset;
  576. while (segmentStartPos < startOffset + sectionLength) {
  577. if (dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos + 1) === 0x02) {
  578. segmentType = dataView.getUint8(segmentStartPos + 2);
  579. if (segmentType in IptcFieldMap) {
  580. dataSize = dataView.getInt16(segmentStartPos + 3);
  581. segmentSize = dataSize + 5;
  582. fieldName = IptcFieldMap[segmentType];
  583. fieldValue = getStringFromDB(dataView, segmentStartPos + 5, dataSize);
  584. // Check if we already stored a value with this name
  585. if (data.hasOwnProperty(fieldName)) {
  586. // Value already stored with this name, create multivalue field
  587. if (data[fieldName] instanceof Array) {
  588. data[fieldName].push(fieldValue);
  589. } else {
  590. data[fieldName] = [data[fieldName], fieldValue];
  591. }
  592. } else {
  593. data[fieldName] = fieldValue;
  594. }
  595. }
  596. }
  597. segmentStartPos++;
  598. }
  599. return data;
  600. }
  601. function readTags(file: DataView, tiffStart: number, dirStart: number, strings: any[], bigEnd: number) {
  602. let entries = file.getUint16(dirStart, !bigEnd),
  603. tags = {},
  604. entryOffset, tag;
  605. for (let i = 0; i < entries; i++) {
  606. entryOffset = dirStart + i * 12 + 2;
  607. tag = strings[file.getUint16(entryOffset, !bigEnd)];
  608. if (!tag && exif.debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
  609. tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
  610. }
  611. return tags;
  612. }
  613. function readTagValue(file: DataView, entryOffset: number, tiffStart: number, dirStart: number, bigEnd: number) {
  614. let type = file.getUint16(entryOffset + 2, !bigEnd),
  615. numValues = file.getUint32(entryOffset + 4, !bigEnd),
  616. valueOffset = file.getUint32(entryOffset + 8, !bigEnd) + tiffStart,
  617. offset,
  618. vals, val, n,
  619. numerator, denominator;
  620. switch (type) {
  621. case 1: // byte, 8-bit unsigned int
  622. case 7: // undefined, 8-bit byte, value depending on field
  623. if (numValues == 1) {
  624. return file.getUint8(entryOffset + 8, !bigEnd);
  625. } else {
  626. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  627. vals = [];
  628. for (n = 0; n < numValues; n++) {
  629. vals[n] = file.getUint8(offset + n);
  630. }
  631. return vals;
  632. }
  633. case 2: // ascii, 8-bit byte
  634. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  635. return getStringFromDB(file, offset, numValues - 1);
  636. case 3: // short, 16 bit int
  637. if (numValues == 1) {
  638. return file.getUint16(entryOffset + 8, !bigEnd);
  639. } else {
  640. offset = numValues > 2 ? valueOffset : (entryOffset + 8);
  641. vals = [];
  642. for (n = 0; n < numValues; n++) {
  643. vals[n] = file.getUint16(offset + 2 * n, !bigEnd);
  644. }
  645. return vals;
  646. }
  647. case 4: // long, 32 bit int
  648. if (numValues == 1) {
  649. return file.getUint32(entryOffset + 8, !bigEnd);
  650. } else {
  651. vals = [];
  652. for (n = 0; n < numValues; n++) {
  653. vals[n] = file.getUint32(valueOffset + 4 * n, !bigEnd);
  654. }
  655. return vals;
  656. }
  657. case 5: // rational = two long values, first is numerator, second is denominator
  658. if (numValues == 1) {
  659. numerator = file.getUint32(valueOffset, !bigEnd);
  660. denominator = file.getUint32(valueOffset + 4, !bigEnd);
  661. val = new Number(numerator / denominator);
  662. val.numerator = numerator;
  663. val.denominator = denominator;
  664. return val;
  665. } else {
  666. vals = [];
  667. for (n = 0; n < numValues; n++) {
  668. numerator = file.getUint32(valueOffset + 8 * n, !bigEnd);
  669. denominator = file.getUint32(valueOffset + 4 + 8 * n, !bigEnd);
  670. vals[n] = new Number(numerator / denominator);
  671. vals[n].numerator = numerator;
  672. vals[n].denominator = denominator;
  673. }
  674. return vals;
  675. }
  676. case 9: // slong, 32 bit signed int
  677. if (numValues == 1) {
  678. return file.getInt32(entryOffset + 8, !bigEnd);
  679. } else {
  680. vals = [];
  681. for (n = 0; n < numValues; n++) {
  682. vals[n] = file.getInt32(valueOffset + 4 * n, !bigEnd);
  683. }
  684. return vals;
  685. }
  686. case 10: // signed rational, two slongs, first is numerator, second is denominator
  687. if (numValues == 1) {
  688. return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset + 4, !bigEnd);
  689. } else {
  690. vals = [];
  691. for (n = 0; n < numValues; n++) {
  692. vals[n] = file.getInt32(valueOffset + 8 * n, !bigEnd) / file.getInt32(valueOffset + 4 + 8 *
  693. n, !bigEnd);
  694. }
  695. return vals;
  696. }
  697. }
  698. }
  699. /**
  700. * Given an IFD (Image File Directory) start offset
  701. * returns an offset to next IFD or 0 if it's the last IFD.
  702. */
  703. function getNextIFDOffset(dataView: DataView, dirStart: number, bigEnd: number) {
  704. //the first 2bytes means the number of directory entries contains in this IFD
  705. var entries = dataView.getUint16(dirStart, !bigEnd);
  706. // After last directory entry, there is a 4bytes of data,
  707. // it means an offset to next IFD.
  708. // If its value is '0x00000000', it means this is the last IFD and there is no linked IFD.
  709. return dataView.getUint32(dirStart + 2 + entries * 12, !bigEnd); // each entry is 12 bytes long
  710. }
  711. function readThumbnailImage(dataView: DataView, tiffStart: number, firstIFDOffset: number, bigEnd: number) {
  712. // get the IFD1 offset
  713. const IFD1OffsetPointer = getNextIFDOffset(dataView, tiffStart + firstIFDOffset, bigEnd);
  714. if (!IFD1OffsetPointer) {
  715. // console.log('******** IFD1Offset is empty, image thumb not found ********');
  716. return {};
  717. } else if (IFD1OffsetPointer > dataView.byteLength) { // this should not happen
  718. // console.log('******** IFD1Offset is outside the bounds of the DataView ********');
  719. return {};
  720. }
  721. // console.log('******* thumbnail IFD offset (IFD1) is: %s', IFD1OffsetPointer);
  722. let thumbTags : any = readTags(dataView, tiffStart, tiffStart + IFD1OffsetPointer, IFD1Tags, bigEnd)
  723. // EXIF 2.3 specification for JPEG format thumbnail
  724. // If the value of Compression(0x0103) Tag in IFD1 is '6', thumbnail image format is JPEG.
  725. // Most of Exif image uses JPEG format for thumbnail. In that case, you can get offset of thumbnail
  726. // by JpegIFOffset(0x0201) Tag in IFD1, size of thumbnail by JpegIFByteCount(0x0202) Tag.
  727. // Data format is ordinary JPEG format, starts from 0xFFD8 and ends by 0xFFD9. It seems that
  728. // JPEG format and 160x120pixels of size are recommended thumbnail format for Exif2.1 or later.
  729. if (thumbTags['Compression'] && typeof Blob !== 'undefined') {
  730. // console.log('Thumbnail image found!');
  731. switch (thumbTags['Compression']) {
  732. case 6:
  733. // console.log('Thumbnail image format is JPEG');
  734. if (thumbTags.JpegIFOffset && thumbTags.JpegIFByteCount) {
  735. // extract the thumbnail
  736. var tOffset = tiffStart + thumbTags.JpegIFOffset;
  737. var tLength = thumbTags.JpegIFByteCount;
  738. thumbTags['blob'] = new Blob([new Uint8Array(dataView.buffer, tOffset, tLength)], {
  739. type: 'image/jpeg'
  740. });
  741. }
  742. break;
  743. case 1:
  744. console.log("Thumbnail image format is TIFF, which is not implemented.");
  745. break;
  746. default:
  747. console.log("Unknown thumbnail image format '%s'", thumbTags['Compression']);
  748. }
  749. } else if (thumbTags['PhotometricInterpretation'] == 2) {
  750. console.log("Thumbnail image format is RGB, which is not implemented.");
  751. }
  752. return thumbTags;
  753. }
  754. function getStringFromDB(buffer: DataView, start: number, length: number) {
  755. let outstr = "";
  756. for (let n = start; n < start + length; n++) {
  757. outstr += String.fromCharCode(buffer.getUint8(n));
  758. }
  759. return outstr;
  760. }
  761. function readEXIFData(file: DataView, start: number) {
  762. if (getStringFromDB(file, start, 4) != "Exif") {
  763. if (exif.debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
  764. return false;
  765. }
  766. let bigEnd,
  767. tags, tag,
  768. exifData, gpsData,
  769. tiffOffset = start + 6;
  770. // test for TIFF validity and endianness
  771. if (file.getUint16(tiffOffset) == 0x4949) {
  772. bigEnd = false;
  773. } else if (file.getUint16(tiffOffset) == 0x4D4D) {
  774. bigEnd = true;
  775. } else {
  776. if (exif.debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  777. return false;
  778. }
  779. if (file.getUint16(tiffOffset + 2, !bigEnd) != 0x002A) {
  780. if (exif.debug) console.log("Not valid TIFF data! (no 0x002A)");
  781. return false;
  782. }
  783. const firstIFDOffset = file.getUint32(tiffOffset + 4, !bigEnd);
  784. if (firstIFDOffset < 0x00000008) {
  785. if (exif.debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset + 4,
  786. !bigEnd));
  787. return false;
  788. }
  789. tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
  790. if (tags.ExifIFDPointer) {
  791. exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
  792. for (tag in exifData) {
  793. switch (tag) {
  794. case "LightSource":
  795. case "Flash":
  796. case "MeteringMode":
  797. case "ExposureProgram":
  798. case "SensingMethod":
  799. case "SceneCaptureType":
  800. case "SceneType":
  801. case "CustomRendered":
  802. case "WhiteBalance":
  803. case "GainControl":
  804. case "Contrast":
  805. case "Saturation":
  806. case "Sharpness":
  807. case "SubjectDistanceRange":
  808. case "FileSource":
  809. exifData[tag] = StringValues[tag][exifData[tag]];
  810. break;
  811. case "ExifVersion":
  812. case "FlashpixVersion":
  813. exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2],
  814. exifData[tag][3]);
  815. break;
  816. case "ComponentsConfiguration":
  817. exifData[tag] =
  818. StringValues.Components[exifData[tag][0]] +
  819. StringValues.Components[exifData[tag][1]] +
  820. StringValues.Components[exifData[tag][2]] +
  821. StringValues.Components[exifData[tag][3]];
  822. break;
  823. }
  824. tags[tag] = exifData[tag];
  825. }
  826. }
  827. if (tags.GPSInfoIFDPointer) {
  828. gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
  829. for (tag in gpsData) {
  830. switch (tag) {
  831. case "GPSVersionID":
  832. gpsData[tag] = gpsData[tag][0] +
  833. "." + gpsData[tag][1] +
  834. "." + gpsData[tag][2] +
  835. "." + gpsData[tag][3];
  836. break;
  837. }
  838. tags[tag] = gpsData[tag];
  839. }
  840. }
  841. // extract thumbnail
  842. tags['thumbnail'] = readThumbnailImage(file, tiffOffset, firstIFDOffset, bigEnd);
  843. return tags;
  844. }
  845. function findXMPinJPEG(file: ArrayBuffer) {
  846. if (!('DOMParser' in self)) {
  847. // console.warn('XML parsing not supported without DOMParser');
  848. return;
  849. }
  850. const dataView = new DataView(file);
  851. if (exif.debug) console.log("Got file of length " + file.byteLength);
  852. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  853. if (exif.debug) console.log("Not a valid JPEG");
  854. return false; // not a valid jpeg
  855. }
  856. let offset = 2,
  857. length = file.byteLength,
  858. dom = new DOMParser();
  859. while (offset < (length - 4)) {
  860. if (getStringFromDB(dataView, offset, 4) == "http") {
  861. const startOffset = offset - 1;
  862. const sectionLength = dataView.getUint16(offset - 2) - 1;
  863. let xmpString = getStringFromDB(dataView, startOffset, sectionLength)
  864. const xmpEndIndex = xmpString.indexOf('xmpmeta>') + 8;
  865. xmpString = xmpString.substring(xmpString.indexOf('<x:xmpmeta'), xmpEndIndex);
  866. const indexOfXmp = xmpString.indexOf('x:xmpmeta') + 10
  867. //Many custom written programs embed xmp/xml without any namespace. Following are some of them.
  868. //Without these namespaces, XML is thought to be invalid by parsers
  869. xmpString = xmpString.slice(0, indexOfXmp) +
  870. 'xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" ' +
  871. 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
  872. 'xmlns:tiff="http://ns.adobe.com/tiff/1.0/" ' +
  873. 'xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus" ' +
  874. 'xmlns:ext="http://www.gettyimages.com/xsltExtension/1.0" ' +
  875. 'xmlns:exif="http://ns.adobe.com/exif/1.0/" ' +
  876. 'xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#" ' +
  877. 'xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" ' +
  878. 'xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ' +
  879. 'xmlns:xapGImg="http://ns.adobe.com/xap/1.0/g/img/" ' +
  880. 'xmlns:Iptc4xmpExt="http://iptc.org/std/Iptc4xmpExt/2008-02-29/" ' +
  881. xmpString.slice(indexOfXmp)
  882. var domDocument = dom.parseFromString(xmpString, 'text/xml');
  883. return xml2Object(domDocument);
  884. } else {
  885. offset++;
  886. }
  887. }
  888. }
  889. function xml2json(xml: any) {
  890. var json = {};
  891. if (xml.nodeType == 1) { // element node
  892. if (xml.attributes.length > 0) {
  893. json['@attributes'] = {};
  894. for (var j = 0; j < xml.attributes.length; j++) {
  895. var attribute = xml.attributes.item(j);
  896. json['@attributes'][attribute.nodeName] = attribute.nodeValue;
  897. }
  898. }
  899. } else if (xml.nodeType == 3) { // text node
  900. return xml.nodeValue;
  901. }
  902. // deal with children
  903. if (xml.hasChildNodes()) {
  904. for (var i = 0; i < xml.childNodes.length; i++) {
  905. var child = xml.childNodes.item(i);
  906. var nodeName = child.nodeName;
  907. if (json[nodeName] == null) {
  908. json[nodeName] = xml2json(child);
  909. } else {
  910. if (json[nodeName].push == null) {
  911. var old = json[nodeName];
  912. json[nodeName] = [];
  913. json[nodeName].push(old);
  914. }
  915. json[nodeName].push(xml2json(child));
  916. }
  917. }
  918. }
  919. return json;
  920. }
  921. function xml2Object(xml: any) {
  922. try {
  923. var obj = {};
  924. if (xml.children.length > 0) {
  925. for (var i = 0; i < xml.children.length; i++) {
  926. var item = xml.children.item(i);
  927. var attributes = item.attributes;
  928. for (var idx in attributes) {
  929. var itemAtt = attributes[idx];
  930. var dataKey = itemAtt.nodeName;
  931. var dataValue = itemAtt.nodeValue;
  932. if (dataKey !== undefined) {
  933. obj[dataKey] = dataValue;
  934. }
  935. }
  936. var nodeName = item.nodeName;
  937. if (typeof (obj[nodeName]) == "undefined") {
  938. obj[nodeName] = xml2json(item);
  939. } else {
  940. if (typeof (obj[nodeName].push) == "undefined") {
  941. var old = obj[nodeName];
  942. obj[nodeName] = [];
  943. obj[nodeName].push(old);
  944. }
  945. obj[nodeName].push(xml2json(item));
  946. }
  947. }
  948. } else {
  949. obj = xml.textContent;
  950. }
  951. return obj;
  952. } catch (e) {
  953. console.log(e.message);
  954. }
  955. }