How to strip image metadata in the browser before

2019-04-09 06:25发布

问题:

I am uploading images to a node js server, and sending them to AWS S3 for use on my site. Images that were taken on iOS devices sometimes show up sideways in the browser and I've already figured out that it's due to some of the metadata that iOS attaches to every image which includes the orientation of the phone at the time of capturing the image. It seems like all images which were taken in portrait orientation are flipped sideways in certain browsers (including Chrome on OSX).

I am able to strip the metadata in node and upload to amazon, however the images are still sideways when they reach the node server.

Seems like the most efficient solution would be to strip the metadata when the client selects the image files, and upload them with the correct orientation, however I realize that it's also possible to detect the metadata orientation and flip the image accordingly from the node server.

The problem with flipping it server side is: 1. Too expensive performance-wise. 2. The client still see's a sideways image in the browser preview before uploading.

TL;DR:

So I'm just wondering if anyone could point me in the right direction for how to remove metadata from an image in the browser, while the image is being displayed to the user?

Thanks <3

回答1:

I ran into basically the same problem at work. We didn't find a way to remove the metadata. Instead we solved it by using exif.js to read the metadata, and then drew the image onto a canvas while rotating it appropriately. Vaguely something like this:

var exif = EXIF.findEXIFinJPEG(binary);

switch(exif.Orientation){
    case 1: //no change needed
        break;
    case 2: //horizontal flip
        context.translate(imageWidth, 0);
        context.scale(-1, 1);
        break;

    ...

    case 8: //rotate 90 deg left
        context.rotate(-0.5 * Math.PI);
        context.translate(-imageWidth, 0);
        break;
}

context.drawImage(image, 0, 0, imageWidth, imageHeight);

Hopefully that points you in the right direction.