Mobile image upload rotation, compression solution

Source: Internet
Author: User

On the phone through the page input tag photo upload pictures, some phones will appear the picture rotated 90 degrees D problem, including the IPhone and individual Samsung phones. These phones only appear when the camera is on the vertical, and the photos are displayed in a horizontal picture. Therefore, you can solve this problem by taking the camera angle of the phone to rotate the photo.

Orientation

This parameter is not available for all pictures, but the picture taken by the phone is with this parameter.

Rotation Angle parameter Values
1
Clockwise 90° 6
90° counterclockwise 8
180° 3

The parameter is 1 when the display is normal, then the horizontal beat display normal, that is Orientation = 1 of the phone, the vertical beat parameter is 6.

To get the Orientation parameter, you can do this through the Exif.js library. Exif.js a lot of functions, volume is also very large, uncompressed before a full 30k, which for mobile phone page load is very big impact. And I just need to get Orientation information, so I've cut some code from the Exif.js library here, and reduced the code to a few kilobytes.

Exif.js Get Orientation:

EXIF.getData(file, function() {      var Orientation = EXIF.getTag(this, 'Orientation');});

File is the one uploaded by the input file form. Uploaded files after filereader.readasdataurl (file) can be implemented to preview the picture, which is unclear can be viewed: HTML5 Advanced Series: File upload download

Rotating

Rotation requires the use of the canvas's rotate () method.

ctx.rotate(angle);

The parameters of the rotate method are rotational radians. Need to convert angle to radian: degrees * math.pi/180

The center point of rotation is by default at the beginning of the canvas, i.e. (0, 0). The principle of rotation is as follows:

After rotation, if DrawImage () is performed from (0, 0) points, then the position drawn is in the position of 90 degrees of rotation in the left image, not in the visible area. After the rotation, the axis also rotates, want to display in the visual area, you need to (0, 0) point to the y-axis of the inverse direction of y units, the starting point is (0, y).

Similarly, you can get a rotation of 90 degrees after the starting point is (-X, 0), the starting point after the rotation of 180 degrees is (-X,-y).

Compression
The photos taken by the mobile phone are too large, and using Base64 encoded photos will be larger than the original photo, then the upload when compression is very necessary. Now the cell phone pixel is so high, the photos taken out of the width of the thousands of pixels, canvas to render the photo will be relatively slow.

So the first step is to limit the width and height of the uploaded photos, and to determine if the widths or heights exceed the range, then compress them to a higher width.

var ratio = width / height;if(imgWidth > imgHeight && imgWidth > xx){    imgWidth = xx;    imgHeight = Math.ceil(xx / ratio);}else if(imgWidth < imgHeight && imgHeight > yy){    imgWidth = Math.ceil(yy * ratio);    imgHeight = yy;}

The second step is to compress the photo quality using the Canvas.todataurl () method.

canvas.toDataURL("image/jpeg", 1);

The Todataurl () method returns a data URI containing the image presentation. With two parameters, the first parameter is a picture format, and the default is Image/png. The second parameter is compression quality, which allows you to select the quality of the picture from 0 to 1 in the case where the picture format is Image/jpeg or IMAGE/WEBP.

Summarize

To synthesize the above, the example code includes a streamlined Exif.js library address: File-demo

The main core code is as follows:

<input type= "file" id= "Files" ><script src= "Small-exif.js" ></ Script><script>var IPT = document.getElementById (' Files '), img = document.getElementById (' preview '), Orient  ation = Null;ipt.onchange = function () {var file = Ipt.files[0], reader = new FileReader (), image = new            Image ();        if (file) {exif.getdata (file, function () {Orientation = Exif.gettag (this, ' Orientation ');        });            Reader.onload = function (ev) {image.src = Ev.target.result;                Image.onload = function () {var imgwidth = this.width, imgheight = this.height;  Control the width and height of uploaded images if (ImgWidth > ImgHeight && imgwidth >) {imgwidth                    = 750;                ImgHeight = Math.ceil (* this.height/this.width);  }else if (ImgWidth < imgheight && imgheight > 1334) {                  ImgWidth = Math.ceil (1334 * this.width/this.height);                ImgHeight = 1334; } var canvas = document.createelement ("Canvas"), CTX = Canvas.getcontext (' 2d                ');                Canvas.width = ImgWidth;                Canvas.height = ImgHeight;  if (Orientation && Orientation! = 1) {switch (Orientation) {case 6://                                Rotation 90 degrees canvas.width = imgheight;                                Canvas.height = ImgWidth;                            Ctx.rotate (MATH.PI/2);                            (0,-imgheight) The starting point obtained from the rotation schematic ctx.drawimage (this, 0,-imgheight, ImgWidth, imgheight);                        Break                                Case 3://Rotation 180 degrees ctx.rotate (MATH.PI); Ctx.drawimage (This,-imgwidth,-imgheight, imgwidth, IMGheight);                        Break                                Case 8://Rotation-90 degrees canvas.width = imgheight;                                Canvas.height = ImgWidth;                                Ctx.rotate (3 * MATH.PI/2);                            Ctx.drawimage (this,-imgwidth, 0, ImgWidth, imgheight);                    Break                }}else{ctx.drawimage (this, 0, 0, ImgWidth, imgheight);            } IMG.SRC = Canvas.todataurl ("Image/jpeg", 0.8);    }} reader.readasdataurl (file); }}</script>

Original address: http://blog.gdfengshuo.com/article/17/

Mobile image upload rotation, compression solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.