Home Web Front-end JS Tutorial Solution to the problem of rotation and compression of mobile image uploads

Solution to the problem of rotation and compression of mobile image uploads

Oct 15, 2018 pm 05:20 PM
upload picture Image Compression Picture rotation Mobile terminal

This article will bring you solutions to the problems of rotation and compression of mobile image uploads. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

When you take photos and upload pictures through the input tag of the web page on your mobile phone, some mobile phones will have the problem of the picture being rotated 90 degrees. Includes iPhone and individual Samsung 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 get 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 not sure about this, you can check: HTML5 Advanced Series: File Upload and Download

Rotation

Rotation requires 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:

Rotation schematic

Solution to the problem of rotation and compression of mobile image uploadsAfter rotation, if you perform drawImage() from the (0, 0) point, the drawn position will be the position after rotating 90 degrees in the left picture, which 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 ).

Similarly, 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 the mobile phone are too large, and the photos encoded using base64 will be larger than the original photos, so upload them Compression is very necessary. 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  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
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 a simplified exif.js library address: file-demo

Main The core code is as follows:

<input><img  src="/static/imghw/default1.png" data-src="blank.gif" class="lazy" alt="Solution to the problem of rotation and compression of mobile image uploads" >
<script></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 to the problem of rotation and compression of mobile image uploads那里获得的起始点
                        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
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more related tutorials, please visit

JavaScript Video Tutorial

,

jQuery Video Tutorial, bootstrap Tutorial!

The above is the detailed content of Solution to the problem of rotation and compression of mobile image uploads. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 handle image compression when saving remote images using PHP? How to handle image compression when saving remote images using PHP? Jul 15, 2023 pm 03:57 PM

How to handle image compression when saving remote images using PHP? In actual development, we often need to obtain images from the network and save them to the local server. However, some remote images may be too large, which requires us to compress them to reduce storage space and increase loading speed. PHP provides some powerful extensions to handle image compression, the most commonly used of which are the GD library and the Imagick library. The GD library is a popular image processing library that provides many functions for creating, editing and saving images. Here is a use

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

How to use mobile gesture operations in Vue projects How to use mobile gesture operations in Vue projects Oct 08, 2023 pm 07:33 PM

How to use mobile gesture operations in Vue projects With the popularity of mobile devices, more and more applications need to provide a more friendly interactive experience on the mobile terminal. Gesture operation is one of the common interaction methods on mobile devices, which allows users to complete various operations by touching the screen, such as sliding, zooming, etc. In the Vue project, we can implement mobile gesture operations through third-party libraries. The following will introduce how to use gesture operations in the Vue project and provide specific code examples. First, we need to introduce a special

Solve the problem of multi-touch points on Vue mobile terminal Solve the problem of multi-touch points on Vue mobile terminal Jun 30, 2023 pm 01:06 PM

In mobile development, we often encounter the problem of multi-finger touch. When users use multiple fingers to swipe or zoom the screen on a mobile device, how to accurately recognize and respond to these gestures is an important development challenge. In Vue development, we can take some measures to solve the problem of multi-finger touch on the mobile terminal. 1. Use the vue-touch plug-in vue-touch is a gesture plug-in for Vue, which can easily handle multi-finger touch events on the mobile side. We can install vue-to via npm

How to use JavaScript to achieve image rotation effect? How to use JavaScript to achieve image rotation effect? Oct 20, 2023 pm 07:09 PM

How to use JavaScript to achieve image rotation effect? In web development, we often encounter scenarios where image rotation effects need to be achieved, such as displaying 360° rotation images of products, achieving image carousel effects, etc. JavaScript is a powerful scripting language that can easily achieve this image rotation effect. The following will introduce a method to achieve image rotation effects based on JavaScript and provide specific code examples. First, we create a simple HTML structure

Steps to implement image uploading and display using CakePHP framework Steps to implement image uploading and display using CakePHP framework Jul 29, 2023 pm 04:21 PM

Steps to implement image upload and display using CakePHP framework Introduction: In modern web applications, image upload and display are common functional requirements. The CakePHP framework provides developers with powerful functions and convenient tools, making it simple and efficient to upload and display images. This article will introduce you to how to use the CakePHP framework to upload and display images. Step 1: Create a file upload form First, we need to create a form in the view file for users to upload images. The following is an example of

Use uniapp to implement image rotation function Use uniapp to implement image rotation function Nov 21, 2023 am 11:58 AM

Using uniapp to implement image rotation function In mobile application development, we often encounter scenarios where images need to be rotated. For example, the angle needs to be adjusted after taking a photo, or an effect similar to the rotation of a camera after taking a photo is achieved. This article will introduce how to use the uniapp framework to implement the image rotation function and provide specific code examples. uniapp is a cross-platform development framework based on Vue.js, which can simultaneously develop and publish applications for iOS, Android, H5 and other platforms. Implemented in uniapp

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

See all articles