Accessing JPEG EXIF Rotation Data in Browser-Side JavaScript
When working with JPEG images, it's often desirable to preserve their original orientation information captured by the camera. This data is stored in the EXIF component of JPEG files. To access this data client-side using JavaScript, there are a few steps to follow:
Read the JPEG File:
Parse the EXIF Data:
Find the Orientation Tag:
Here's an example JavaScript code snippet that performs these steps:
<code class="javascript">function getOrientation(file, callback) { var reader = new FileReader(); reader.onload = function(e) { var view = new DataView(e.target.result); var orientation = -1; if (view.getUint16(0, false) == 0xFFD8) { var length = view.byteLength, offset = 2; while (offset < length) { var marker = view.getUint16(offset, false); if (marker == 0xFFE1) { orientation = view.getUint16(offset + (i * 12) + 8, little); break; } else if ((marker & 0xFF00) != 0xFF00) { break; } else { offset += view.getUint16(offset, false); } } } callback(orientation); }; reader.readAsArrayBuffer(file); }</code>
This code requires a file input element to select the JPEG file. The getOrientation function can then be called with the file object to retrieve the orientation value, which can be used to rotate the image accordingly.
The above is the detailed content of How to Access JPEG EXIF Rotation Data in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!