Home  >  Article  >  Web Front-end  >  Use exfe.js and canvas to solve the problem of flipping pictures when taking pictures and uploading them on mobile IOS (with code)

Use exfe.js and canvas to solve the problem of flipping pictures when taking pictures and uploading them on mobile IOS (with code)

不言
不言forward
2018-11-16 17:26:174738browse

The content of this article is about using exfe.js and canvas to solve the problem of flipping photos and uploading pictures on the mobile IOS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

I remember that it was about a year after I first started working on the front end. The company made a webapp with the function of uploading avatars. I was not in charge of this project at the time. During the test, I found that when Apple users took pictures and uploaded avatars, they would flip. At that time, several front-end My classmate spent the entire afternoon trying to solve the problem, but the problem was transferred to me, and I had half an hour to go from get off work. I was also confused at the time, and the first thing that came to my mind was, how can I tell whether it has flipped? There is no problem with Android, and there is no problem with some pictures in the album of Apple mobile phones. Can js have this function to judge? I checked the information online, and sure enough, there is! That is exfe.js. I continued to study. At this time, the team leader sister had already bought dinner, and the boss also came to express condolences. Finally, it was around 9 o'clock in the evening, and it was finally solved.

After two years, I encountered this problem again yesterday. I have left my previous company for a year and a half. The current company is doing a Halloween event, which also involves uploading pictures and synthesizing ghost faces. This was done two days ago. I sent it to the project manager (we are remote here and have a few developers). When I was about to get off work in the evening, the project manager sent a message, "Flip the ios image, fix it, I have to go online tonight, and I will work overtime." I was worried. The grass and mud horses galloped by. First, I forgot that iOS has this problem. Second, it has been sent to you for 2 days. When you were about to get off work, you told me that there was a problem and you had to work overtime! I have to cancel my plans for the evening! Still free! There was no consolation meal, and there was no apology. I was still willing to work overtime, and replied with a wry smile, "Okay, I'll test it in advance next time." After all, I had encountered it this time, and it was handled faster, and it was done after 7 o'clock. If there are any subsequent deployment problems, it’s not my problem anymore. It’s almost 9 o’clock again.

It’s just an almost similar scene, just sighing.

Upload the code

html part

<input type="file" accept="image/*" id="uploadImage" capture="camera" onchange="selectFileImage(this);" />
<img alt="preview" src="" id="myImage"/>

exfe.js to read the image information. There is a lot of information in the image we uploaded

//获取照片方向角属性,用户旋转控制
EXIF.getData(file, function() {
    EXIF.getAllTags(this);
    Orientation = EXIF.getTag(this, 'Orientation');
    console.log(Orientation);
});

Orientation The values ​​​​are 1, 3, 6, 8, etc., respectively representing 0°, 180°, 90° clockwise, and 90° counterclockwise

When we know the rotation angle of the image, we can use Canvas handles them, and finally we get the results we want. Here is an excerpt of a piece of code from the Internet. If there are special functions, you have to write some logic yourself, that is, judge the angle, judge the operating system, and then redraw it with canvas. Generate base64, and finally operate the dom to display the image.

UPCode

function selectFileImage(fileObj) {
        var file = fileObj.files['0'];
        //图片方向角 
        var Orientation = null;
        if (file) {
            //获取照片方向角属性,用户旋转控制
            EXIF.getData(file, function() {
                EXIF.getAllTags(this);
                Orientation = EXIF.getTag(this, 'Orientation');
                console.log(Orientation)
            });
            var oReader = new FileReader();
            oReader.onload = function(e) {
                var image = new Image();
                image.src = e.target.result;
                image.onload = function() {
                    var expectWidth = this.naturalWidth;
                    var expectHeight = this.naturalHeight;

                    if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                        expectWidth = 800;
                        expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                    } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                        expectHeight = 1200;
                        expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                    }
                    var canvas = document.createElement("canvas");
                    var ctx = canvas.getContext("2d");
                    canvas.width = expectWidth;
                    canvas.height = expectHeight;
                    ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                    var base64 = null;
                    //修复ios
                    if (navigator.userAgent.match(/iphone/i)) {
                        console.log('iphone');
                        //如果方向角不为1,都需要进行旋转 
                        if(Orientation != "" && Orientation != 1){
                            alert('旋转处理');
                            switch(Orientation){
                                case 6://需要顺时针(向左)90度旋转
                                    rotateImg(this,'left',canvas);
                                    break;
                                case 8://需要逆时针(向右)90度旋转
                                    rotateImg(this,'right',canvas);
                                    break;
                                case 3://需要180度旋转
                                    rotateImg(this,'right',canvas);//转两次
                                    rotateImg(this,'right',canvas);
                                    break;
                            }
                        }
                        base64 = canvas.toDataURL("image/jpeg", 1);
                    }else if (navigator.userAgent.match(/Android/i)) {// 修复android
                        var encoder = new JPEGEncoder();
                        base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
                    }else{
                        if(Orientation != "" && Orientation != 1){
                            switch(Orientation){
                                case 6://需要顺时针(向左)90度旋转
                                    rotateImg(this,'left',canvas);
                                    break;
                                case 8://需要逆时针(向右)90度旋转
                                    rotateImg(this,'right',canvas);
                                    break;
                                case 3://需要180度旋转
                                    rotateImg(this,'right',canvas);//转两次
                                    rotateImg(this,'right',canvas);
                                    break;
                            }
                        }

                        base64 = canvas.toDataURL("image/jpeg", 1);
                    }
                    $("#myImage").attr("src", base64);
                };
            };
            oReader.readAsDataURL(file);
        }
    }

    //对图片旋转处理 
    function rotateImg(img, direction,canvas) {
        //最小与最大旋转方向,图片旋转4次后回到原方向
        var min_step = 0;
        var max_step = 3;
        if (img == null)return;
        //img的高度和宽度不能在img元素隐藏后获取,否则会出错
        var height = img.height;
        var width = img.width;
        //var step = img.getAttribute('step');
        var step = 2;
        if (step == null) {
            step = min_step;
        }
        if (direction == 'right') {
            step++;
            //旋转到原位置,即超过最大值
            step > max_step && (step = min_step);
        } else {
            step--;
            step < min_step && (step = max_step);
        }
        //旋转角度以弧度值为参数
        var degree = step * 90 * Math.PI / 180;
        var ctx = canvas.getContext('2d');
        switch (step) {
            case 0:
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0);
                break;
            case 1:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, 0, -height);
                break;
            case 2:
                canvas.width = width;
                canvas.height = height;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, -height);
                break;
            case 3:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, 0);
                break;
        }
    }

The above is the detailed content of Use exfe.js and canvas to solve the problem of flipping pictures when taking pictures and uploading them on mobile IOS (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete