JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

前端 未结 12 1113
花落未央
花落未央 2020-11-22 11:59

Digital camera photos are often saved as JPEG with an EXIF \"orientation\" tag. To display correctly, images need to be rotated/mirrored depending on which orientation is se

12条回答
  •  佛祖请我去吃肉
    2020-11-22 12:23

    ok in addition to @user3096626 answer i think it will be more helpful if someone provided code example, the following example will show you how to fix image orientation comes from url (remote images):


    Solution 1: using javascript (recommended)

    1. because load-image library doesn't extract exif tags from url images only (file/blob), we will use both exif-js and load-image javascript libraries, so first add these libraries to your page as the follow:

      
      
      
      
      

      Note the version 2.2 of exif-js seems has issues so we used 2.1

    2. then basically what we will do is

      a - load the image using window.loadImage()

      b - read exif tags using window.EXIF.getData()

      c - convert the image to canvas and fix the image orientation using window.loadImage.scale()

      d - place the canvas into the document

    here you go :)

    window.loadImage("/your-image.jpg", function (img) {
      if (img.type === "error") {
        console.log("couldn't load image:", img);
      } else {
        window.EXIF.getData(img, function () {
            var orientation = EXIF.getTag(this, "Orientation");
            var canvas = window.loadImage.scale(img, {orientation: orientation || 0, canvas: true});
            document.getElementById("container").appendChild(canvas); 
            // or using jquery $("#container").append(canvas);
    
        });
      }
    });
    

    of course also you can get the image as base64 from the canvas object and place it in the img src attribute, so using jQuery you can do ;)

    $("#my-image").attr("src",canvas.toDataURL());
    

    here is the full code on: github: https://github.com/digital-flowers/loadimage-exif-example


    Solution 2: using html (browser hack)

    there is a very quick and easy hack, most browsers display the image in the right orientation if the image is opened inside a new tab directly without any html (LOL i don't know why), so basically you can display your image using iframe by putting the iframe src attribute as the image url directly:

    
    

    Solution 3: using css (only firefox & safari on ios)

    there is css3 attribute to fix image orientation but the problem it is only working on firefox and safari/ios it is still worth mention because soon it will be available for all browsers (Browser support info from caniuse)

    img {
       image-orientation: from-image;
    }
    

提交回复
热议问题