Handle Exif orientations for JPEG images (fixes #1670) #2296
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Implements simple Exif parsing for JPEG files, enough to determine if there is an Exif tag, and if that tag has an orientation, rotates the image. This makes node-canvas compatible with browsers, which also rotate the image based on the Exif orientation tag. This fixes #1670.
A simple test program for 2 of the 3 paths follows. This loads the JPEG, draws it to the canvas, and saves the result to
./test.png
. Test images are available (among other places) from https://github.com/noell/jpg-exif-test-images:`
const fs = require('fs')
const { createCanvas, loadImage } = require('canvas')
// One source of sample images with EXIF rotations is at
// https://github.com/noell/jpg-exif-test-images
const imagePath = process.argv[2];
loadImage(imagePath).then(image => {
const w = image.naturalWidth
const h = image.naturalHeight
const canvas = createCanvas(w, h/, 'PDF'/) // uncomment to test the mime device path
const context = canvas.getContext('2d')
context.fillStyle = '#f0f';
context.fillRect(0, 0, w, h);
context.drawImage(image, 0, 0, w, h)
}).catch(e => {
console.log("[error]", e);
})
`
Since one major use of
node-canvas
is in thefabric
project, which has not updated to the newly release 3.0 version yet, I think it would be helpful to backport to 2.11 (they use 2.11.2 at the moment), since it seems that 3.0 makes breaking changes for fabric. I initially made these changes on a branch from the v2.11.2 tag, and they merged with no problems, so I expect this changeset can be merged into a 2.11 branch. I can also create a separate pull request to whatever branch would be appropriate, if that is helpful.