Home > Web Front-end > JS Tutorial > How to use JS to rotate the preview of IOS photo taken by 90 degrees

How to use JS to rotate the preview of IOS photo taken by 90 degrees

php中世界最好的语言
Release: 2018-04-17 16:43:10
Original
1661 people have browsed it

This time I will show you how to use JS to rotate the preview of the IOS photo taken by 90 degrees, and how to use JS to process the preview of the IOS photo taken 90 degrees by rotating it 90 degrees. , let’s take a look. To solve this problem, you need to introduce a third-party JS library: exif.js Download address:

https://

github.com/exif-js/exif-js Through exif.js we can obtain the meta information of the image , which includes the direction in which the photo was taken. The photo direction

attribute

given by exif.js is used in IOS to obtain the direction of the photographed picture through exif.js. The returned value is 6, which is the case of the leftmost F in the above picture. This is where our bug lies. Therefore, we perform corresponding processing by judging the value of the direction. If the value is 6, we perform rotation correction on the image. The specific code is as follows:

//获取图片方向
function getPhotoOrientation(img) {
   var orient;
   EXIF.getData(img, function () {
      orient = EXIF.getTag(this, 'Orientation');
   });
   return orient;
}
Copy after login

Next, we will modify the compression function in the previous article as follows:

//图片压缩
function compress(img, width, height, ratio) {
   var canvas, ctx, img64, orient;
    
   //获取图片方向
   orient = getPhotoOrientation(img);
   canvas = document.createElement('canvas');
   canvas.width = width;
   canvas.height = height;
   ctx = canvas.getContext("2d");
   //如果图片方向等于6 ,则旋转矫正,反之则不做处理
   if (orient == 6) {
      ctx.save();
      ctx.translate(width / 2, height / 2);
      ctx.rotate(90 * Math.PI / 180);
      ctx.drawImage(img, 0 - height / 2, 0 - width / 2, height, width);
      ctx.restore();
   } else {
      ctx.drawImage(img, 0, 0, width, height);
   }
   img64 = canvas.toDataURL("image/jpeg", ratio);
   return img64;
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:



The above is the detailed content of How to use JS to rotate the preview of IOS photo taken by 90 degrees. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template