Home > Web Front-end > JS Tutorial > How to Access JPEG EXIF Rotation Data in JavaScript on the Client Side?

How to Access JPEG EXIF Rotation Data in JavaScript on the Client Side?

Susan Sarandon
Release: 2024-11-04 07:28:31
Original
778 people have browsed it

How to Access JPEG EXIF Rotation Data in JavaScript on the Client Side?

Accessing JPEG EXIF Rotation Data in JavaScript on the Client Side

Problem:

Rotating photos based on their original rotation, as recorded in JPEG EXIF data, is a challenge when working with JavaScript and local images in the browser.

Client-Side Solution:

To address this problem, we require a client-side solution that enables JavaScript to extract orientation information from JPEG EXIF data. One approach involves utilizing the FileReader API and DataView objects:

<br>function getOrientation(file, callback) {<br>  const reader = new FileReader();<br>  reader.onload = (e) => {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

let length = view.byteLength, offset = 2;
while (offset < length) {
  if (view.getUint16(offset+2, false) <= 8) return callback(-1);
  const marker = view.getUint16(offset, false);
  offset += 2;
  if (marker == 0xFFE1) {
    if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);

    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));
      }
    }
  } else if ((marker &amp; 0xFF00) != 0xFF00) break;
  else offset += view.getUint16(offset, false);
}
return callback(-1);
Copy after login

};
reader.readAsArrayBuffer(file);
}

This code snippet exemplifies a client-side solution that extracts the orientation tag from JPEG EXIF data. By utilizing FileReader and DataView, it swiftly and effectively retrieves the desired information.

The above is the detailed content of How to Access JPEG EXIF Rotation Data in JavaScript on the Client Side?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template