Decoding EXIF Orientation for JPEG Image Correction on the Client Side
Digital camera photos often use EXIF metadata to specify their orientation. However, browsers generally ignore this information, leading to incorrect image display on web applications. The issue arises due to the numerous possible orientations that a JPEG image can have.
To address this issue, the JavaScript-Load-Image project provides a solution for rotating and mirroring JPEG images based on their EXIF orientation. This ensures accurate display and subsequent processing of images.
Features
Solution Example
To incorporate JavaScript-Load-Image into your application, simply include it as a dependency. The following demonstration illustrates how to use the library to rotate and mirror an image based on EXIF orientation:
<code class="javascript">import loadImage from 'javascript-load-image'; const imageElement = document.getElementById('my-image'); loadImage(imageElement, (image) => { // Get the EXIF orientation value const orientation = image.exif && image.exif.Orientation; // Perform rotation and mirroring transformations based on orientation if (orientation) { const width = image.naturalWidth; const height = image.naturalHeight; const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const context = canvas.getContext('2d'); switch (orientation) { case 1: // Normal // No transformation required break; case 2: // Mirrored horizontally context.translate(width, 0); context.scale(-1, 1); break; case 3: // Rotated 180 degrees context.translate(width, height); context.rotate(Math.PI); break; case 4: // Mirrored vertically context.translate(0, height); context.scale(1, -1); break; case 5: // Rotated 90 degrees CCW, mirrored horizontally context.translate(0, width); context.rotate(-Math.PI / 2); break; case 6: // Rotated 90 degrees CCW context.translate(height, 0); context.rotate(Math.PI / 2); break; case 7: // Rotated 90 degrees CW, mirrored horizontally context.translate(width, 0); context.rotate(Math.PI / 2); context.scale(-1, 1); break; case 8: // Rotated 90 degrees CW context.translate(height, width); context.rotate(-Math.PI / 2); break; } context.drawImage(image, 0, 0); imageElement.src = canvas.toDataURL('image/jpeg'); } });</code>
Benefits
By utilizing JavaScript-Load-Image, you can:
The above is the detailed content of How to Correctly Display JPEG Images with EXIF Orientation on the Client Side?. For more information, please follow other related articles on the PHP Chinese website!