Accessing JPEG EXIF Rotation Data in JavaScript on the Client Side
The EXIF data embedded in JPEG images holds valuable information, including the original rotation of the photo. To enhance user experience, developers often need access to this EXIF data for automatic rotation adjustments. This article presents a JavaScript solution to retrieve JPEG EXIF rotation data on the client side.
How to Retrieve JPEG EXIF Rotation Data
To access JPEG EXIF data in JavaScript, you can employ the following steps:
Example Code
Here's an example code snippet that implements the steps described above:
<code class="javascript">function getOrientation(file, callback) { // Read the JPEG file const reader = new FileReader(); reader.onload = function(e) { const arrayBuffer = e.target.result; // Parse the EXIF data const view = new DataView(arrayBuffer); if (view.getUint16(0, false) != 0xFFD8) { return callback(-2); // Not a JPEG file } let offset = 2; while (offset < arrayBuffer.byteLength) { if (view.getUint16(offset + 2, false) <= 8) return callback(-1); // Invalid JPEG file const marker = view.getUint16(offset, false); offset += 2; if (marker == 0xFFE1) { if (view.getUint32(offset += 2, false) != 0x45786966) { return callback(-1); // Not an EXIF header } // Find the orientation tag const little = view.getUint16(offset += 6, false) == 0x4949; offset += view.getUint32(offset + 4, little); const tags = view.getUint16(offset, little); offset += 2; for (let i = 0; i < tags; i++) { if (view.getUint16(offset + (i * 12), little) == 0x0112) { return callback(view.getUint16(offset + (i * 12) + 8, little)); // Found the orientation tag } } } else if ((marker & 0xFF00) != 0xFF00) { break; // Not a valid JPEG marker } else { offset += view.getUint16(offset, false); // Skip the rest of the segment } } return callback(-1); // Orientation tag not found }; reader.readAsArrayBuffer(file); } // Usage: const input = document.getElementById('input'); input.onchange = function(e) { getOrientation(input.files[0], function(orientation) { alert('Orientation: ' + orientation); }); };</code>
This code snippet can be integrated into your web application to retrieve and process JPEG EXIF rotation data, allowing you to rotate photos based on their original orientation on the client side.
The above is the detailed content of How to Extract JPEG EXIF Rotation Data in JavaScript on the Client Side?. For more information, please follow other related articles on the PHP Chinese website!