Home  >  Article  >  Web Front-end  >  How to Access JPEG EXIF Rotation Data in JavaScript?

How to Access JPEG EXIF Rotation Data in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 19:15:02701browse

How to Access JPEG EXIF Rotation Data in JavaScript?

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:

  1. Read the JPEG File:

    • Use the FileReader API to read the local JPEG file or retrieve it from a remote source when it's already loaded as an image element ().
  2. Parse the EXIF Data:

    • Once the file is read, the EXIF data can be extracted by creating a DataView object from the result.
    • Loop through the DataView until the EXIF header (0xFFE1) is found.
  3. Find the Orientation Tag:

    • Parse the EXIF data to locate the Orientation tag (0x0112). The tag's value represents the required rotation in degrees.

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 &amp; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn