### Install piexif from source Source: https://github.com/hmatoba/piexifjs/blob/master/docs/installation.md Download the source code, extract it, and run the setup script for installation. This method is useful for development or offline installations. ```default $ python setup.py install ``` -------------------------------- ### Install piexif with easy_install Source: https://github.com/hmatoba/piexifjs/blob/master/docs/installation.md Use easy_install for installing piexif. Ensure easy_install is available in your environment. ```default $ easy_install piexif ``` -------------------------------- ### Install piexif with pip Source: https://github.com/hmatoba/piexifjs/blob/master/docs/installation.md Use pip, the recommended package installer for Python, to install piexif. This is the most common installation method. ```default $ pip install piexif ``` -------------------------------- ### Install piexifjs via NPM Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Use this command to install the library if you are working in a Node.js environment. ```bash npm install piexifjs ``` -------------------------------- ### Install piexifjs v1.0.4 Source: https://github.com/hmatoba/piexifjs/blob/master/README.rst Install a specific version of the piexifjs library using npm. ```bash npm install piexifjs@1.0.4 ``` -------------------------------- ### Example: Modify EXIF Data with File API Source: https://github.com/hmatoba/piexifjs/blob/master/README.rst This example demonstrates how to read a file, modify its EXIF data using piexifjs, and display the result. It requires an input element with id 'files' and assumes piexif.js is loaded. ```html ``` -------------------------------- ### Set Flash Fired Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Example of setting the EXIF Flash tag to indicate that the flash fired. Requires the piexif library. ```javascript exif[piexif.ExifIFD.Flash] = 1; // Flash fired ``` -------------------------------- ### piexif.insert() - Given data is not exif. Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/errors.md This error occurs when the first argument provided to `piexif.insert()` is not valid EXIF data, meaning it does not start with the expected 'Exif\x00\x00' header. Only data generated by `piexif.dump()` is considered valid. ```APIDOC ## piexif.insert() - Given data is not exif. ### Description This error occurs when the first argument provided to `piexif.insert()` is not valid EXIF data, meaning it does not start with the expected 'Exif\x00\x00' header. Only data generated by `piexif.dump()` is considered valid. ### How to handle: Always use the result of `piexif.dump()` as the first argument to ensure valid EXIF data is passed. ### Example: ```javascript function safeInsertExif(exifDict, jpegData) { try { var exifBytes = piexif.dump(exifDict); // Produces valid EXIF data return piexif.insert(exifBytes, jpegData); } catch (e) { console.error("Failed to insert EXIF:", e.message); return null; } } ``` ``` -------------------------------- ### IFD Dictionary Example Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/types.md An example of an IFD (Image File Directory) dictionary, showing how tag IDs are used as keys and their corresponding values. This structure is used for '0th', 'Exif', 'GPS', and '1st' sections of the ExifObject. ```javascript var exifObj = { "0th": { 271: "Canon", // Make (ImageIFD tag 271) 272: "EOS 5D", // Model (ImageIFD tag 272) 305: "Adobe Lightroom 5.0", // Software (ImageIFD tag 305) 36867: "2023:06:15 14:30:45" // DateTimeOriginal (ExifIFD tag 36867) }, "Exif": { 33434: [1, 125], // ExposureTime (1/125 second) 33437: [28, 10], // FNumber (f/2.8) 34855: 400 // ISOSpeedRatings (ISO 400) }, "GPS": { 0: [2, 2, 0, 0], // GPSVersionID 2: [[48, 1], [51, 1], [1234, 100]] // GPSLatitude (DMS format) }, "Interop": {}, "1st": {}, "thumbnail": null }; ``` -------------------------------- ### Handling Resolution Settings Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/imageifd-tags.md This example shows how to set image resolution using XResolution, YResolution, and ResolutionUnit tags. It covers common values for web (72 DPI) and print (300 DPI) standards, and demonstrates using centimeters as a unit. ```javascript var zeroth = {}; // 72 DPI (web standard) zeroth[piexif.ImageIFD.XResolution] = [72, 1]; zeroth[piexif.ImageIFD.YResolution] = [72, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 2; // inches // 300 DPI (print standard) zeroth[piexif.ImageIFD.XResolution] = [300, 1]; zeroth[piexif.ImageIFD.YResolution] = [300, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 2; // inches // 118 DPI with centimeter units zeroth[piexif.ImageIFD.XResolution] = [118, 1]; zeroth[piexif.ImageIFD.YResolution] = [118, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 3; // centimeters ``` -------------------------------- ### Load EXIF Data from JPEG Source: https://github.com/hmatoba/piexifjs/blob/master/README.rst Use piexif.load() to get EXIF data as an object. The input must be a DataURL, binary string starting with \xff\xd8, or 'Exif'. ```javascript var exifObj = piexif.load(jpegData) ``` -------------------------------- ### Handle Invalid EXIF Data for piexif.insert() Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/errors.md Throws an error if the first argument to `piexif.insert()` is not valid EXIF data, meaning it doesn't start with the 'Exif\x00\x00' header. Always use the output of `piexif.dump()` to ensure valid EXIF data. ```javascript // Throws error: passes random binary data try { var jpeg = piexif.insert("some random data", jpegData); } catch (e) { console.log(e.message); // "Given data is not exif." } // Throws error: passes EXIF data without the header var exifWithoutHeader = exifBytes.slice(6); // Remove "Exif\x00\x00" try { var jpeg = piexif.insert(exifWithoutHeader, jpegData); } catch (e) { console.log(e.message); // "Given data is not exif." } ``` ```javascript function safeInsertExif(exifDict, jpegData) { try { var exifBytes = piexif.dump(exifDict); // Produces valid EXIF data return piexif.insert(exifBytes, jpegData); } catch (e) { console.error("Failed to insert EXIF:", e.message); return null; } } ``` -------------------------------- ### Load EXIF Data from Raw JPEG Binary (Node.js) Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/api-reference-core.md Example of loading EXIF data from a raw JPEG binary file using Node.js's file system module. The file is read as a binary string. ```javascript // Load from raw JPEG binary (Node.js) var fs = require('fs'); var jpegData = fs.readFileSync('photo.jpg').toString('binary'); var exifObj = piexif.load(jpegData); ``` -------------------------------- ### Set Light Source Constant Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Sets the LightSource EXIF tag to Daylight. This example demonstrates setting the light source within an exif object. ```javascript exif[piexif.ExifIFD.LightSource] = 1; // Daylight ``` -------------------------------- ### Load EXIF Data from DataURL (Browser) Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/api-reference-core.md Example of loading EXIF data from a DataURL, typically obtained from the browser's File API. Requires a FileReader to read the file content. ```javascript // Load from DataURL (browser File API) var reader = new FileReader(); reader.onload = function(e) { var exifObj = piexif.load(e.target.result); console.log(exifObj["0th"][piexif.ImageIFD.Make]); }; reader.readAsDataURL(file); ``` -------------------------------- ### Reading Interop Information from JPEG Data Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Provides a comprehensive example of loading EXIF data from a JPEG, checking for the presence of Interop data, and interpreting the InteroperabilityIndex value. ```APIDOC ## Reading Interop Information ```javascript var exifObj = piexif.load(jpegData); var interopData = exifObj["Interop"]; if (Object.keys(interopData).length > 0) { if (piexif.InteropIFD.InteroperabilityIndex in interopData) { var interopIndex = interopData[piexif.InteropIFD.InteroperabilityIndex]; console.log("Interoperability Index:", interopIndex); if (interopIndex === "R98") { console.log("Standard EXIF/JPEG format"); } else if (interopIndex === "R03") { console.log("JPEG 2000 format"); } else if (interopIndex === "THM") { console.log("Thumbnail image"); } } } ``` ``` -------------------------------- ### piexif.insert() - Given data is not jpeg. Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/errors.md This error is raised when the second argument to `piexif.insert()` is not recognized as valid JPEG data. Valid inputs include raw JPEG binary data starting with '\xff\xd8' or DataURLs for JPEG images. ```APIDOC ## piexif.insert() - Given data is not jpeg. ### Description This error is raised when the second argument to `piexif.insert()` is not recognized as valid JPEG data. Valid inputs include raw JPEG binary data starting with '\xff\xd8' or DataURLs for JPEG images. ### How to handle: Validate the JPEG data using a helper function before attempting to insert EXIF data. ### Example: ```javascript function isValidJpeg(data) { if (typeof data !== 'string') return false; var header = data.slice(0, 23); return ( data.slice(0, 2) === "\xff\xd8" || header === "data:image/jpeg;base64," || data.slice(0, 22) === "data:image/jpg;base64," ); } function safeInsert(exifBytes, jpegData) { if (!isValidJpeg(jpegData)) { console.error("JPEG data is invalid"); return null; } return piexif.insert(exifBytes, jpegData); } ``` ``` -------------------------------- ### Handle 'Given thumbnail is too large. max 64kB' Error in piexif.dump() Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/errors.md This example demonstrates how to handle the error when the thumbnail data in an EXIF dictionary exceeds the 64KB limit for piexif.dump(). It provides two strategies: removing the thumbnail if it's too large or validating the size before dumping. ```javascript var exifDict = { "0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "thumbnail": largeJpegData // > 64KB }; try { var exifBytes = piexif.dump(exifDict); } catch (e) { console.log(e.message); // "Given thumbnail is too large. max 64kB" } ``` ```javascript function dumpExifWithValidation(exifDict) { // Option 1: Remove thumbnail if too large if (exifDict["thumbnail"] && exifDict["thumbnail"].length > 65536) { console.warn("Thumbnail exceeds 64KB, removing it"); exifDict["thumbnail"] = null; } // Option 2: Validate before dumping if (exifDict["thumbnail"]) { if (exifDict["thumbnail"].length > 65536) { throw new Error("Thumbnail must be <= 64KB"); } } return piexif.dump(exifDict); } ``` -------------------------------- ### Insert EXIF into JPEG (Node.js) Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/api-reference-core.md This Node.js example demonstrates how to read a JPEG file, create new EXIF data (even an empty object), insert it into the JPEG binary data, and then write the modified image to a new file. Ensure you have 'fs' module available. ```javascript // Node.js: insert and save to file var fs = require('fs'); var jpegBinary = fs.readFileSync('original.jpg').toString('binary'); var exifBytes = piexif.dump({"0th": {}}); var newJpeg = piexif.insert(exifBytes, jpegBinary); fs.writeFileSync('output.jpg', Buffer.from(newJpeg, 'binary')); ``` -------------------------------- ### Set Color Space sRGB Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Example of setting the ColorSpace EXIF tag to sRGB (1) using piexifjs. ```javascript exif[piexif.ExifIFD.ColorSpace] = 1; // sRGB ``` -------------------------------- ### Import piexifjs in Node.js Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Require the piexifjs module after installation for use in your Node.js project. ```javascript var piexif = require('piexifjs'); ``` -------------------------------- ### Handle ''load' gots invalid type argument.' Error in piexif.load() Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/errors.md This example shows how to handle the error when piexif.load() receives an input that is not a string, such as a Buffer or Uint8Array. It includes methods for converting binary data to a string in both Node.js and browser environments. ```javascript // Throws error: passes Uint8Array or Buffer try { var buffer = Buffer.from([0xFF, 0xD8]); var exifObj = piexif.load(buffer); // Error! } catch (e) { console.log(e.message); // "'load' gots invalid type argument." } ``` ```javascript // Node.js: convert Buffer to binary string var fs = require('fs'); var jpegBuffer = fs.readFileSync('photo.jpg'); var jpegString = jpegBuffer.toString('binary'); var exifObj = piexif.load(jpegString); // Browser: use FileReader for Blob/File var file = document.getElementById('fileInput').files[0]; var reader = new FileReader(); reader.onload = function(e) { // e.target.result is already a string (DataURL or binary) var exifObj = piexif.load(e.target.result); }; reader.readAsDataURL(file); // Returns DataURL string // Or: reader.readAsBinaryString(file) for binary string ``` -------------------------------- ### Basic EXIF Workflow Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Demonstrates the four-step process: loading existing EXIF data, modifying it, dumping it to binary, and inserting it back into a JPEG. ```javascript // Step 1: Load existing EXIF var exifObj = piexif.load(jpegData); // Step 2: Modify exifObj["0th"][piexif.ImageIFD.Software] = "My Photo Editor"; // Step 3: Dump to binary var exifBytes = piexif.dump(exifObj); // Step 4: Insert into JPEG var newJpeg = piexif.insert(exifBytes, jpegData); ``` -------------------------------- ### Create EXIF Data from Scratch Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Shows how to construct a new EXIF data structure, including image metadata (0th IFD), photo settings (Exif IFD), and GPS data (GPS IFD), then dump it into bytes and insert into a JPEG. ```javascript // Create empty EXIF structure var zeroth = {}; var exif = {}; var gps = {}; // Add image metadata (0th IFD) zeroth[piexif.ImageIFD.Make] = "Canon"; zeroth[piexif.ImageIFD.Model] = "EOS 5D"; zeroth[piexif.ImageIFD.Software] = "Adobe Lightroom"; zeroth[piexif.ImageIFD.DateTime] = "2023:06:15 14:30:45"; // Add photo settings (Exif IFD) exif[piexif.ExifIFD.DateTimeOriginal] = "2023:06:15 14:30:45"; exif[piexif.ExifIFD.FocalLength] = [50, 1]; exif[piexif.ExifIFD.FNumber] = [28, 10]; exif[piexif.ExifIFD.ISOSpeedRatings] = 400; exif[piexif.ExifIFD.ExposureTime] = [1, 125]; // Add GPS data (GPS IFD) gps[piexif.GPSIFD.GPSVersionID] = [2, 2, 0, 0]; gps[piexif.GPSIFD.GPSLatitudeRef] = "N"; gps[piexif.GPSIFD.GPSLatitude] = [[48, 1], [51, 1], [12345, 100]]; gps[piexif.GPSIFD.GPSLongitudeRef] = "E"; gps[piexif.GPSIFD.GPSLongitude] = [[2, 1], [17, 1], [54321, 100]]; // Create and dump EXIF var exifDict = {"0th": zeroth, "Exif": exif, "GPS": gps}; var exifBytes = piexif.dump(exifDict); // Insert into JPEG var newJpeg = piexif.insert(exifBytes, originalJpegData); ``` -------------------------------- ### Example GPS DMS for Paris Latitude Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/types.md An example of how to represent the latitude of Paris (48°51'23.76"N) in the GPS DMS rational format. ```javascript [[48, 1], [51, 1], [2376, 100]] ``` -------------------------------- ### piexif.load(jpegData) Source: https://github.com/hmatoba/piexifjs/blob/master/docs/functions.md Retrieves EXIF data from a JPEG image as a JavaScript object. The input can be a DataURL, a byte string starting with \xff\xd8, or a string starting with 'Exif'. ```APIDOC ## piexif.load(jpegData) ### Description Get exif data as *object*. jpegData must be a *string* that starts with “data:image/jpeg;base64,”(DataURL), “\xff\xd8”, or “Exif”. ### Method `piexif.load` ### Parameters #### Arguments - **jpegData** (`string`) – JPEG data ### Returns Exif data({“0th”:object, “Exif”:object, “GPS”:object, “Interop”:object, “1st”:object, “thumbnail”:string}) ### Return type object ### Example ```javascript var exifObj = piexif.load(jpegData); for (var ifd in exifObj) { if (ifd == "thumbnail") { continue; } console.log("-" + ifd); for (var tag in exifObj[ifd]) { console.log(" " + piexif.TAGS[ifd][tag]["name"] + ":" + exifObj[ifd][tag]); } } ``` ``` -------------------------------- ### Work with GPS Data using Helper Functions Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Demonstrates using `piexif.GPSHelper` to convert decimal degrees to the rational DMS format required for GPS tags and vice-versa. Includes setting GPS version, latitude/longitude references, and altitude. ```javascript // Using helper to convert decimal degrees to DMS var lat = 48.8566; // Paris var lon = 2.3522; // Paris var gps = {}; gps[piexif.GPSIFD.GPSVersionID] = [2, 2, 0, 0]; gps[piexif.GPSIFD.GPSLatitudeRef] = "N"; gps[piexif.GPSIFD.GPSLatitude] = piexif.GPSHelper.degToDmsRational(lat); gps[piexif.GPSIFD.GPSLongitudeRef] = "E"; gps[piexif.GPSIFD.GPSLongitude] = piexif.GPSHelper.degToDmsRational(lon); gps[piexif.GPSIFD.GPSAltitudeRef] = 0; gps[piexif.GPSIFD.GPSAltitude] = [100, 1]; // Reading GPS data back var exifObj = piexif.load(jpegData); if (piexif.GPSIFD.GPSLatitude in exifObj["GPS"]) { var latDMS = exifObj["GPS"][piexif.GPSIFD.GPSLatitude]; var latRef = exifObj["GPS"][piexif.GPSIFD.GPSLatitudeRef]; var latitude = piexif.GPSHelper.dmsRationalToDeg(latDMS, latRef); console.log("Latitude:", latitude); } ``` -------------------------------- ### Create EXIF Dictionary from Scratch Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/README.md Create a new EXIF data structure from scratch. This involves defining the different IFDs (Image, Exif, GPS, etc.) and their tags. ```javascript var exifDict = { "0th": { [piexif.ImageIFD.Make]: "Canon" }, "Exif": { [piexif.ExifIFD.DateTimeOriginal]: "2023:06:15 14:30:45" }, "GPS": {}, "Interop": {}, "1st": {}, "thumbnail": null }; ``` -------------------------------- ### Load EXIF Data from JPEG Source: https://github.com/hmatoba/piexifjs/blob/master/docs/functions.md Use this function to extract EXIF data from JPEG data. The input can be a DataURL, a hex string starting with \xff\xd8, or a string starting with 'Exif'. ```javascript var exifObj = piexif.load(jpegData); for (var ifd in exifObj) { if (ifd == "thumbnail") { continue; } console.log("-" + ifd); for (var tag in exifObj[ifd]) { console.log(" " + piexif.TAGS[ifd][tag]["name"] + ":" + exifObj[ifd][tag]); } } ``` -------------------------------- ### Set Resolution and Unit Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Demonstrates setting image resolution in DPI for inches and pixels per centimeter for centimeters using piexifjs. ```javascript // 72 DPI (dots per inch) zeroth[piexif.ImageIFD.XResolution] = [72, 1]; zeroth[piexif.ImageIFD.YResolution] = [72, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 2; // inches // 300 DPI (print standard) zeroth[piexif.ImageIFD.XResolution] = [300, 1]; zeroth[piexif.ImageIFD.YResolution] = [300, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 2; // 118 pixels per centimeter zeroth[piexif.ImageIFD.XResolution] = [118, 1]; zeroth[piexif.ImageIFD.YResolution] = [118, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 3; // centimeters ``` -------------------------------- ### Accessing piexifjs in Different Environments Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/module-structure.md Illustrates how to import or include the piexifjs library in Node.js, a web browser, and ES6 module environments. ```javascript // Node.js var piexif = require('piexifjs'); ``` ```html // Browser // window.piexif is now available ``` ```javascript // ES6 modules (with transpiler) import piexif from 'piexifjs'; ``` -------------------------------- ### Get piexifjs Version Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Retrieves the current version of the piexifjs library. ```javascript piexif.version // string: "1.0.4" ``` -------------------------------- ### Creating an EXIF Dictionary with Interop IFD Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Illustrates how to construct an EXIF dictionary that includes the Interop IFD, specifically setting the InteroperabilityIndex for standard EXIF compatibility. ```APIDOC ## Creating Interop IFD for Standard EXIF ```javascript var exifDict = { "0th": { /* main image metadata */ }, "Exif": { /* photo settings */ }, "Interop": { [piexif.InteropIFD.InteroperabilityIndex]: "R98" } }; var exifBytes = piexif.dump(exifDict); ``` ``` -------------------------------- ### Automatic Management of InteroperabilityTag Pointer Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Explains and demonstrates how piexif.dump() automatically handles the relationship between the Exif IFD's InteroperabilityTag and the Interop IFD when Interop data is present. ```APIDOC ## Relationship to Other IFDs ```javascript // The library automatically manages this relationship var exifDict = { "0th": {}, "Exif": {}, "Interop": { [piexif.InteropIFD.InteroperabilityIndex]: "R98" } }; // When dumped, piexif automatically: // 1. Includes the Interop IFD in output // 2. Sets Exif IFD tag 40965 (InteroperabilityTag) to point to Interop IFD var exifBytes = piexif.dump(exifDict); ``` ``` -------------------------------- ### Read and Write EXIF Data in Node.js Source: https://github.com/hmatoba/piexifjs/blob/master/docs/sample.md Demonstrates reading an image file, manipulating EXIF data (including GPS, 0th, and Exif IFDs), and writing the modified image back to a file using Node.js. ```javascript var piexif = require("piexifjs"); var fs = require("fs"); var filename1 = "in.jpg"; var filename2 = "out.jpg"; var jpeg = fs.readFileSync(filename1); var data = jpeg.toString("binary"); var zeroth = {}; var exif = {}; var gps = {}; zeroth[piexif.ImageIFD.Make] = "Make"; zeroth[piexif.ImageIFD.XResolution] = [777, 1]; zeroth[piexif.ImageIFD.YResolution] = [777, 1]; zeroth[piexif.ImageIFD.Software] = "Piexifjs"; exif[piexif.ExifIFD.DateTimeOriginal] = "2010:10:10 10:10:10"; exif[piexif.ExifIFD.LensMake] = "LensMake"; exif[piexif.ExifIFD.Sharpness] = 777; exif[piexif.ExifIFD.LensSpecification] = [[1, 1], [1, 1], [1, 1], [1, 1]]; gps[piexif.GPSIFD.GPSVersionID] = [7, 7, 7, 7]; gps[piexif.GPSIFD.GPSDateStamp] = "1999:99:99 99:99:99"; var exifObj = {"0th":zeroth, "Exif":exif, "GPS":gps}; var exifbytes = piexif.dump(exifObj); var newData = piexif.insert(exifbytes, data); var newJpeg = Buffer.from(newData, "binary"); fs.writeFileSync(filename2, newJpeg); ``` -------------------------------- ### Access EXIF Tag Metadata Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/types.md Use piexif.TAGS to get human-readable names and types for EXIF tags. IFD name aliases like '0th' and '1st' map to 'Image'. ```javascript piexif.TAGS[ifd_name][tag_id] = { 'name': string, // Human-readable tag name 'type': string // EXIF type: 'Byte', 'Ascii', 'Short', 'Long', // 'Rational', 'Undefined', 'SLong', 'SRational' } ``` ```javascript // Get metadata for tag 271 (Make) in Image IFD var tagInfo = piexif.TAGS["Image"][271]; // Returns: { 'name': 'Make', 'type': 'Ascii' } // IFD name aliases // "0th" and "1st" IFD use "Image" tag definitions // "Exif", "GPS", "Interop" have their own tag definitions ``` -------------------------------- ### Setting Common Image Properties Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/imageifd-tags.md Use this snippet to set essential image metadata like camera make, model, software, dimensions, resolution, orientation, and date-time. Ensure piexif is imported and exifDict is initialized. ```javascript var zeroth = {}; // Required for valid EXIF zeroth[piexif.ImageIFD.Make] = "Canon"; zeroth[piexif.ImageIFD.Model] = "EOS 5D Mark IV"; zeroth[piexif.ImageIFD.Software] = "Adobe Lightroom 5.0"; // Image dimensions zeroth[piexif.ImageIFD.ImageWidth] = 5760; zeroth[piexif.ImageIFD.ImageLength] = 3840; // Resolution (72 DPI) zeroth[piexif.ImageIFD.XResolution] = [72, 1]; zeroth[piexif.ImageIFD.YResolution] = [72, 1]; zeroth[piexif.ImageIFD.ResolutionUnit] = 2; // 2 = inches // Orientation zeroth[piexif.ImageIFD.Orientation] = 1; // Normal, no rotation // DateTime zeroth[piexif.ImageIFD.DateTime] = "2023:06:15 14:30:45"; var exifDict = {"0th": zeroth}; var exifBytes = piexif.dump(exifDict); ``` -------------------------------- ### Accessing and Setting Interop Data Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Demonstrates how to read the InteroperabilityIndex from an EXIF object and how to set it when creating a new EXIF dictionary. ```APIDOC ## Accessing Interop Data ```javascript var interopIndex = exifObj["Interop"][piexif.InteropIFD.InteroperabilityIndex]; ``` ## Setting Interop Data ```javascript interop[piexif.InteropIFD.InteroperabilityIndex] = "R98"; // Recommended EXIF Interop ``` ``` -------------------------------- ### Accessing and Setting ExifIFD Tags Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/exififd-tags.md Demonstrates how to read specific EXIF tags like shutter speed and set lens information using `piexif.ExifIFD` constants. ```javascript // Read shutter speed var shutterSpeed = exifObj["Exif"][piexif.ExifIFD.ShutterSpeedValue]; // Set lens information exif[piexif.ExifIFD.LensMake] = "Sigma"; exif[piexif.ExifIFD.LensModel] = "24mm f/1.4 Art"; ``` -------------------------------- ### Core Operations with piexifjs Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/README.md Demonstrates the fundamental operations of reading, converting, inserting, and removing EXIF data from JPEG images using the piexifjs library. These functions are essential for basic EXIF manipulation. ```javascript var exifObj = piexif.load(jpegData); // Read EXIF from JPEG ``` ```javascript var exifBytes = piexif.dump(exifObj); // Convert to binary ``` ```javascript var newJpeg = piexif.insert(exifBytes, jpeg); // Insert into JPEG ``` ```javascript var clean = piexif.remove(jpegData); // Remove all EXIF ``` -------------------------------- ### Set Image Orientation Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/constants-and-utilities.md Demonstrates how to set the EXIF Orientation tag to control image rotation. Requires the piexif library. ```javascript zeroth[piexif.ImageIFD.Orientation] = 1; // Normal zeroth[piexif.ImageIFD.Orientation] = 6; // Rotated 90° CW zeroth[piexif.ImageIFD.Orientation] = 8; // Rotated 90° CCW ``` -------------------------------- ### Automatic Management of InteroperabilityTag by piexif.dump() Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Illustrates how piexif.js automatically manages the InteroperabilityTag in the Exif IFD when Interop data is included in the dictionary during the dump process. ```javascript // The library automatically manages this relationship var exifDict = { "0th": {}, "Exif": {}, "Interop": { [piexif.InteropIFD.InteroperabilityIndex]: "R98" } }; // When dumped, piexif automatically: // 1. Includes the Interop IFD in output // 2. Sets Exif IFD tag 40965 (InteroperabilityTag) to point to Interop IFD var exifBytes = piexif.dump(exifDict); ``` -------------------------------- ### Metadata and Helper Properties in piexifjs Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/module-structure.md Provides access to complete tag metadata, GPS coordinate utilities, and the library's version string. ```javascript piexif.TAGS // Complete tag metadata (internal structure) ``` ```javascript piexif.GPSHelper // GPS coordinate conversion utilities ``` ```javascript piexif.version // Library version string (e.g., "1.0.4") ``` -------------------------------- ### Access and Set Interop Data Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/interopifd-tags.md Demonstrates how to access the InteroperabilityIndex from an existing EXIF object and how to set it when creating new EXIF data. ```javascript var exifObj = piexif.load(jpegData); // Access Interop data var interopIndex = exifObj["Interop"][piexif.InteropIFD.InteroperabilityIndex]; // Set Interop data var interop = {}; interop[piexif.InteropIFD.InteroperabilityIndex] = "R98"; // Recommended EXIF Interop ``` -------------------------------- ### Handle File Selection for EXIF Loading Source: https://github.com/hmatoba/piexifjs/blob/master/samples/LoadSample.html Attaches an event listener to an input element to handle file selection. Reads the selected file as a data URL and passes it to the printExif function. ```javascript function handleFileSelect(evt) { var file = evt.target.files[0]; var reader = new FileReader(); reader.onloadend = function(e){ printExif(e.target.result); }; reader.readAsDataURL(file); } document.getElementById('f').addEventListener('change', handleFileSelect, false); ``` -------------------------------- ### piexif.load() Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/api-reference-core.md Loads EXIF data from a given string representing a JPEG image or raw EXIF binary. It returns a structured dictionary containing various EXIF IFDs and potentially thumbnail data. ```APIDOC ## piexif.load() ### Description Loads EXIF data from a JPEG image or raw EXIF binary and returns a structured dictionary. ### Method `piexif.load(data: string)` ### Parameters #### Path Parameters - **data** (string) - Required - JPEG image data or EXIF data. Can be a binary string starting with "\xff\xd8" (JPEG binary), a DataURL string starting with "data:image/jpeg;base64," or "data:image/jpg;base64,", or a raw EXIF string starting with "Exif". ### Response #### Success Response (200) `object` — An EXIF dictionary with the following structure: ```javascript { "0th": { /* Image IFD tags */ }, "Exif": { /* EXIF IFD tags */ }, "GPS": { /* GPS IFD tags */ }, "Interop": { /* Interoperability IFD tags */ }, "1st": { /* First IFD tags for thumbnail */ }, "thumbnail": string | null /* Thumbnail JPEG data or null */ } ``` Keys are numeric EXIF tag IDs (integers). Values depend on the tag type: numbers, strings, arrays of numbers, or arrays of rational pairs `[numerator, denominator]`. ### Throws - `Error`: "Given data is not jpeg." — If data does not start with JPEG magic bytes, DataURL JPEG prefix, or "Exif" header - `Error`: "'load' gots invalid type argument." — If data is not a string - `Error`: "'load' gots invalid file data." — If string has unrecognized format ### Example ```javascript // Load from DataURL (browser File API) var reader = new FileReader(); reader.onload = function(e) { var exifObj = piexif.load(e.target.result); console.log(exifObj["0th"][piexif.ImageIFD.Make]); }; reader.readAsDataURL(file); // Load from raw JPEG binary (Node.js) var fs = require('fs'); var jpegData = fs.readFileSync('photo.jpg').toString('binary'); var exifObj = piexif.load(jpegData); ``` ``` -------------------------------- ### Set and Read GPS Coordinates Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/gpsifd-tags.md Demonstrates how to set GPS latitude reference and latitude, and how to read GPS latitude from an EXIF object. Use piexif.GPSIFD constants as keys for the GPS IFD dictionary. ```javascript // Set GPS coordinates gps[piexif.GPSIFD.GPSLatitudeRef] = "N"; gps[piexif.GPSIFD.GPSLatitude] = [[48, 1], [51, 1], [12345, 100]]; // Read GPS data var latitude = exifObj["GPS"]. [piexif.GPSIFD.GPSLatitude]; ``` -------------------------------- ### piexif.dump(exifObj) Source: https://github.com/hmatoba/piexifjs/blob/master/docs/functions.md Converts an EXIF data object into a binary string format suitable for insertion into a JPEG file. ```APIDOC ## piexif.dump(exifObj) ### Description Get exif binary as *string* to insert into JPEG. ### Method `piexif.dump` ### Parameters #### Arguments - **exifObj** (`object`) – Exif data({“0th”:0thIFD - object, “Exif”:ExifIFD - object, “GPS”:GPSIFD - object, “Interop”:InteroperabilityIFD - object, “1st”:1stIFD - object, “thumbnail”:JPEG data - string}) ### Returns Exif binary ### Return type string ### Example ```javascript var zeroth = {}; var exif = {}; var gps = {}; zeroth[piexif.ImageIFD.Make] = "Make"; zeroth[piexif.ImageIFD.XResolution] = [777, 1]; zeroth[piexif.ImageIFD.YResolution] = [777, 1]; zeroth[piexif.ImageIFD.Software] = "Piexifjs"; exif[piexif.ExifIFD.DateTimeOriginal] = "2010:10:10 10:10:10"; exif[piexif.ExifIFD.LensMake] = "LensMake"; exif[piexif.ExifIFD.Sharpness] = 777; exif[piexif.ExifIFD.LensSpecification] = [[1, 1], [1, 1], [1, 1], [1, 1]]; gps[piexif.GPSIFD.GPSVersionID] = [7, 7, 7, 7]; gps[piexif.GPSIFD.GPSDateStamp] = "1999:99:99 99:99:99"; var exifObj = {"0th":zeroth, "Exif":exif, "GPS":gps}; var exifbytes = piexif.dump(exifObj); ``` Properties of *piexif.ImageIFD* help to make 0thIFD and 1stIFD. *piexif.ExifIFD* is for ExifIFD. *piexif.GPSIFD* is for GPSIFD. *piexif.InteropIFD* is for InteroperabilityIFD. #### NOTE ExifTag(34665), GPSTag(34853), and InteroperabilityTag(40965) in 0thIFD automatically are set appropriate value. #### NOTE JPEGInterchangeFormat(513), and JPEGInterchangeFormatLength(514) in 1stIFD automatically are set appropriate value. #### NOTE If ‘thumbnail’ is contained in *exifObj*, ‘1st’ must be contained – and vice versa. 1stIFD means thumbnail’s information. ``` -------------------------------- ### Core Functions Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/module-structure.md These functions provide the primary interface for interacting with EXIF data. `load` reads EXIF from a JPEG, `dump` converts an EXIF dictionary to binary, `insert` adds EXIF to a JPEG, and `remove` strips EXIF from a JPEG. ```APIDOC ## Core Functions ### `piexif.load(data)` Reads EXIF data from a JPEG file. ### `piexif.dump(exifDict)` Converts an EXIF dictionary into a binary format. ### `piexif.insert(exif, jpeg)` Inserts EXIF binary data into a JPEG file. ### `piexif.remove(jpeg)` Removes EXIF data from a JPEG file. ``` -------------------------------- ### Include piexifjs in Browser Source: https://github.com/hmatoba/piexifjs/blob/master/_autodocs/getting-started.md Include the piexif.js script directly in your HTML for browser usage. The library will be available as `window.piexif`. ```html ``` -------------------------------- ### Load and Display EXIF Data from Image Source: https://github.com/hmatoba/piexifjs/blob/master/samples/LoadSample.html Reads a data URL, loads EXIF data using piexif.load(), and displays it along with the original image and its dimensions. Handles image loading and EXIF parsing. ```javascript function printExif(dataURL) { var originalImg = new Image(); originalImg.src = dataURL; var exif = piexif.load(dataURL); var ifds = ["0th", "Exif", "GPS", "Interop", "1st"]; var s = "" for (var i=0; i<5; i++) { var ifd = ifds[i]; var ifd_i = ""; for (var tag in exif[ifd]) { var str; if (exif[ifd][tag] instanceof Array) { str = JSON.stringify(exif[ifd][tag]); } else { str = escape(exif[ifd][tag]); } ifd_i += ("" + piexif.TAGS[ifd][tag]["name"] + "
" + str + "
"); } s += ("" + ifd_i + "
" + ifd + "
"); } if (exif["thumbnail"]) { var thumbStr = "data:image/jpeg;base64," + btoa(exif["thumbnail"]); var img = "".replace("{img}", thumbStr); s += ("
thumbnail
" + img + "

"); } var newDiv = $("
").html(s).hide(); $("#output").prepend(newDiv); originalImg.onload = function () { var w = originalImg.width; var h = originalImg.height; var size = $("
").text("Original size:" + w + "*" + h); var im = $(originalImg).addClass("originalImage"); newDiv.prepend(im); newDiv.prepend(size); } newDiv.slideDown(2000); } ```