Table of Contents
Preface
Orientation
Home Web Front-end JS Tutorial Solution for mobile image upload, rotation and compression

Solution for mobile image upload, rotation and compression

Jun 30, 2017 pm 01:21 PM
upload compression rotate

Preface

When taking pictures and uploading pictures through the input tag of the web page on a mobile phone, some mobile phones will have the problem of the picture being rotated 90 degrees, including iPhone and individual Samsung mobile phones. This problem only occurs when these phones are taken vertically, and photos taken horizontally display normally. Therefore, you can solve this problem by getting the camera angle of your phone to rotate the photo.

Orientation

This parameter is not available in all pictures, but pictures taken by mobile phones have this parameter.

##0°1##90° clockwise##90° counterclockwise8180°3The display is normal when the parameter is 1, then the display is normal in these horizontal shots, That is, on a mobile phone with Orientation = 1, the vertical shooting parameter is 6.
Rotation angle Parameter value
6
If you want to obtain the Orientation parameter, you can operate it through the exif.js library. exif.js has many functions and is large in size. It is 30k before uncompressed, which has a great impact on mobile page loading. And I only need to get the Orientation information, so I deleted some code from the exif.js library and reduced the code to a few KB.

exif.js Get Orientation:

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

file is the file uploaded by the input file form. The uploaded file can be previewed through fileReader.readAsDataURL(file). If you are unclear about this, you can check: HTML5 Advanced Series: File Upload and Download
Rotation

Rotation needs to be used The rotate() method of canvas.

ctx.rotate(angle);
Copy after login

The parameter of the rotate method is the rotation arc. The angle needs to be converted into radians: degrees * Math.PI / 180
The center point of rotation is at the starting point of the canvas by default, that is (0, 0). The principle of rotation is as follows:

After rotation, if drawImage() is performed from the (0, 0) point, the drawn position will be rotated 90 in the left picture The position behind it is not in the visible area. After the rotation, the coordinate axis also rotates. If you want to display it in the visible area, you need to move the (0, 0) point y units in the opposite direction of the y-axis. The starting point at this time is (0, -y ). Solution for mobile image upload, rotation and compression

In the same way, the starting point after rotating -90 degrees is (-x, 0), and the starting point after rotating 180 degrees is (-x, -y).

Compression

The photos taken by mobile phones are too large, and the photos encoded using base64 will be larger than the original photos, so it is very necessary to compress them when uploading. Today's mobile phones have such high pixels, and the width and height of the photos taken are several thousand pixels. Using canvas to render the photos will be relatively slow.

Therefore, the first step is to limit the width and height of the uploaded photo, determine whether the width or height exceeds the range, and then compress the width and height in equal proportions.

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;}
Copy after login

The second step is to compress the photo quality through the canvas.toDataURL() method.
canvas.toDataURL("image/jpeg", 1);
Copy after login

The toDataURL() method returns a data URI containing the image display. Use two parameters, the first parameter is the image format, the default is image/png. The second parameter is the compression quality. When the specified image format is image/jpeg or image/webp, you can select the image quality from 0 to 1.
Summary

Based on the above, the example code includes the streamlined exif.js library address: file-demo

The main core code is as follows:

<input type="file" id="files" ><img  src="/static/imghw/default1.png"  data-src="blank.gif"  class="lazy"   id="preview" alt="Solution for mobile image upload, rotation and compression" >
<script src="small-exif.js?1.1.11"></script><script>var ipt = document.getElementById(&#39;files&#39;),img = document.getElementById(&#39;preview&#39;),Orientation = 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, &#39;Orientation&#39;);});
            reader.onload = function (ev) {image.src = ev.target.result;
            image.onload = function () {var imgWidth = this.width,imgHeight = this.height;
            // 控制上传图片的宽高if(imgWidth > imgHeight && imgWidth > 750){imgWidth = 750;
            imgHeight = Math.ceil(750 * 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(&#39;2d&#39;);
            canvas.width = imgWidth;canvas.height = imgHeight;
            if(Orientation && Orientation != 1){switch(Orientation){case 6:     
            // 旋转90度canvas.width = imgHeight;    canvas.height = imgWidth;    
            ctx.rotate(Math.PI / 2);
            // (0,-imgHeight) 从Solution for mobile image upload, rotation and compression那里获得的起始点ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
            break;case 3:     // 旋转180度ctx.rotate(Math.PI);    
            ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);break;case 8:     
            // 旋转-90度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>
Copy after login

The above is the detailed content of Solution for mobile image upload, rotation and compression. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable or disable memory compression on Windows 11 How to enable or disable memory compression on Windows 11 Sep 19, 2023 pm 11:33 PM

With memory compression on Windows 11, your device will choke even with a limited amount of RAM. In this article, we will show you how to enable or disable memory compression on Windows 11. What is memory compression? Memory compression is a feature that compresses data before writing it to RAM, thus providing more storage space on it. Of course, more data stored in physical memory translates into faster system operation and better overall performance. This feature is enabled by default in Windows 11, but if it's somehow not active, you can disable or re-enable it. How to enable memory compression in Windows 11? Click the search bar, type powershell, and click

7-zip maximum compression rate setting, how to compress 7zip to the minimum 7-zip maximum compression rate setting, how to compress 7zip to the minimum Jun 18, 2024 pm 06:12 PM

I found that the compressed package downloaded from a download website will be larger than the original compressed package after decompression. The difference is tens of Kb for a small one and several dozen Mb for a large one. If it is uploaded to a cloud disk or paid space, it does not matter if the file is small. , if there are many files, the storage cost will be greatly increased. I studied it specifically and can learn from it if necessary. Compression level: 9-Extreme compression Dictionary size: 256 or 384, the more compressed the dictionary, the slower it is. The compression rate difference is larger before 256MB, and there is no difference in compression rate after 384MB. Word size: maximum 273 Parameters: f=BCJ2, test and add parameter compression rate will be higher

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

How to take photos and upload them on computer How to take photos and upload them on computer Jan 16, 2024 am 10:45 AM

As long as the computer is equipped with a camera, it can take pictures, but some users still don't know how to take pictures and upload them. Now I will give you a detailed introduction to the method of taking pictures on the computer, so that users can upload the pictures wherever they want. How to take photos and upload them on a computer 1. Mac computer 1. Open Finder and click the application on the left. 2. After opening, click the Camera application. 3. Just click the photo button below. 2. Windows computer 1. Open the search box below and enter camera. 2. Then open the searched application. 3. Click the photo button next to it.

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

Tips to reduce win10 screen recording file size Tips to reduce win10 screen recording file size Jan 04, 2024 pm 12:05 PM

Many friends need to record screens for office work or transfer files, but sometimes the problem of files that are too large causes a lot of trouble. The following is a solution to the problem of files that are too large, let’s take a look. What to do if the win10 screen recording file is too large: 1. Download the software Format Factory to compress the file. Download address >> 2. Enter the main page and click the "Video-MP4" option. 3. Click "Add File" on the conversion format page and select the MP4 file to be compressed. 4. Click "Output Configuration" on the page to compress the file according to the output quality. 5. Select "Low Quality and Size" from the drop-down configuration list and click "OK". 6. Click "OK" to complete the import of video files. 7. Click "Start" to start the conversion. 8. After completion, you can

How to rotate Word pictures How to rotate Word pictures Mar 19, 2024 pm 06:16 PM

When we use Word office software for document processing, we often need to insert some pictures and other materials into the document. However, in order to achieve beautiful layout, we also need to perform some special layout on the pictures, among which rotation processing is the most basic. Typesetting processing, however, for some newcomers to the workplace who have just come into contact with Word office software, they may not be able to process pictures in Word documents. Below, we will share how to rotate pictures in Word. We hope it will be helpful and inspiring to you. 1. First, we open a Word document, and then click the Insert-Picture button on the menu bar to insert a random picture on the computer to facilitate our operation and demonstration. 2. If we want to rotate the image, then we need to

See all articles