IOS photo compression inverse time 90°

In the WebView app, ios will rotate when uploading a picture to canvas compression, which has not been found in other models

exif.js

Exif is recognition of data such as photo direction, camera equipment model, shooting time, ISO sensitivity, GPS location and so on.Copy the code

Note: Only read photos taken using devices (such as cameras, mobile phones, cameras, etc.) for testing, such photos have EXIF data.

Exif. Js Gith document

The photo orientation attributes given by exif.js are shown below:

From the picture we can see that our bug is the 6 value in the picture.

The concrete solution

1. When exif.js is introduced, Github can see three ways. We can introduce it directly with CDN.

// Remember to use ~ before the method
<script src="https://cdn.jsdelivr.net/npm/exif-js"></script>
Copy the code

2. Step into the compression process code


ImginClude64 Images without header 64 encoding
// type Upload image type, eg:image/jpeg
// size Upload image size eg:30107
A maximum of 4M, a minimum of 15px on the shortest side and a maximum of 4096px on the longest side
 
function canvasToLower (imginClude64, type, size) 
  let quality = setQuality(size)
  return new Promise((resolve, reject) = >{
    // No request was made
    // See if the image is more than 4m long and wide, and the longest edge is 4096px at most
    var thisImg = new Image();

    thisImg.src = imginClude64;
    thisImg.onload = (a)= > {
      let imgW = thisImg.width
      let imgH = thisImg.height
      if (size > 8000) { / / is more than 0.8 m
        // Create a Canvas object
        let canvas = document.createElement('canvas')
        // Get the corresponding CanvasRenderingContext2D object (brush)
        let context = canvas.getContext('2d')
        // Do not change the width and height
        canvas.width = imgW
        canvas.height = imgH
        let orient = getPhotoOrientation(thisImg)
        // If exif takes a value of 6, rotate it back
        if (orient == 6) {
          context.save();
          context.translate(imgW / 2, imgH / 2);
          context.rotate(90 * Math.PI / 180);
          context.drawImage(thisImg, 0 - imgH / 2.0 - imgW / 2, imgH, imgW);
          context.restore();
        }
        else {
          context.drawImage(thisImg, 0.0, imgW, imgH)
        }

        let smallImg64 = canvas.toDataURL("image/jpeg", quality)
        resolve(smallImg64)
      } else {
        resolve(imginClude64)
      }
    }
  })
}
Copy the code

3. Get the Orient function

// Get the direction of the image
function getPhotoOrientation (img) {
  var orient;
  EXIF.getData(img, function () {
    orient = EXIF.getTag(this.'Orientation');
    console.log('orient2', orient);
  });
  return orient;
}
Copy the code

Reference:

  • The home of the script