When html5+ Canvas is used to upload mobile phone photos, it is found that the vertical photos uploaded by ios phones will rotate 90 degrees counterclockwise, while horizontal photos have no such problem. Android phones don’t have this problem.

Therefore, the idea to solve this problem is to obtain the direction Angle of the photo and correct the Angle rotation of the non-horizontal ios photo.

Using the exif. Js read photo shooting information, see the code.ciaoca.com/javascript/…

The Orientation attribute is used here.

Orientation attributes are described as follows:

Rotation Angle parameter
0 ° 1
Clockwise 90 ° 6
90 ° anticlockwise 8
180 ° 3

 

So let’s go straight to the code.

The main html5 page and a JS, sample features include image compression and rotation.

UploadImage. Js.

The HTML5 test page is as follows:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="Initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" />
    <title>Image upload</title>
    <script type="text/javascript" src="Js/jquery - 1.8.3. Js"></script>
    <script type="text/javascript" src="js/uploadPicture/uploadImage.js" ></script>
        <script type="text/javascript" src="js/exif.js" ></script>
    <script>
 
    </script>
</head>
<body>
	<div style="height: 50px; line-height: 50px; text-align: center; border-bottom: 1px solid #171E28;">Upload pictures:<input type="file" accept="image/*" id="uploadImage" capture="camera" οnchange="selectFileImage(this);" />
		</div>
		<div style="margin-top: 10px;">
			<img alt="preview" src="" id="myImage"/>
		</div>
</body>
</html>
Copy the code

UploadImage. Js as follows:

function selectFileImage(fileObj) {
	var file = fileObj.files['0'];
	Added by LZK
	var Orientation = null;
	
	if (file) {
		console.log("Uploading, please wait...");
		var rFilter = /^(image\/jpeg|image\/png)$/i; // Check the image format
		if(! rFilter.test(file.type)) {//showMyTips(" please select JPEG, PNG ", false);
			return;
		}
		// var URL = URL || webkitURL;
		// Get photo Angle property, user rotation control
		EXIF.getData(file, function() {
		   // alert(EXIF.pretty(this));
		    EXIF.getAllTags(this); 
		    //alert(EXIF.getTag(this, 'Orientation')); 
		    Orientation = EXIF.getTag(this.'Orientation');
		    //return;
		});
		
		var oReader = new FileReader();
		oReader.onload = function(e) {
			//var blob = URL.createObjectURL(file);
			//_compress(blob, file, basePath);
			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;
				/ / repair the ios
				if (navigator.userAgent.match(/iphone/i)) {
					console.log('iphone');
					//alert(expectWidth + ',' + expectHeight);
					Added by LZK if the direction Angle is not 1, add added by LZK
					if(Orientation ! =""&& Orientation ! =1){
						alert('Rotation processing');
						switch(Orientation){
						 	case 6:// Rotate clockwise (left) 90 degrees
						 		alert('Need to rotate 90 degrees clockwise (left)');
						 		rotateImg(this.'left',canvas);
						 		break;
						 	case 8:// Rotate 90 degrees counterclockwise (to the right)
						 		alert('Need to rotate 90 degrees clockwise (to the right)');
						 		rotateImg(this.'right',canvas);
						 		break;
						 	case 3:// Rotate 180 degrees
						 		alert('I need to rotate 180 degrees.');
								rotateImg(this.'right',canvas);/ / twice
								rotateImg(this.'right',canvas);
								break; }}/*var mpImg = new MegaPixImage(image); Render (canvas, {maxWidth: 800, maxHeight: 1200, quality: 0.8, orientation: 8}); * /
					base64 = canvas.toDataURL("image/jpeg".0.8);
				}else if (navigator.userAgent.match(/Android/i)) {/ / repair android
					var encoder = new JPEGEncoder();
					base64 = encoder.encode(ctx.getImageData(0.0, expectWidth, expectHeight), 80);
				}else{
					//alert(Orientation);
					if(Orientation ! =""&& Orientation ! =1) {//alert(' rotate ');
						switch(Orientation){
						 	case 6:// Rotate clockwise (left) 90 degrees
						 		alert('Need to rotate 90 degrees clockwise (left)');
						 		rotateImg(this.'left',canvas);
						 		break;
						 	case 8:// Rotate 90 degrees counterclockwise (to the right)
						 		alert('Need to rotate 90 degrees clockwise (to the right)');
						 		rotateImg(this.'right',canvas);
						 		break;
						 	case 3:// Rotate 180 degrees
						 		alert('I need to rotate 180 degrees.');
								rotateImg(this.'right',canvas);/ / twice
								rotateImg(this.'right',canvas);
								break;
						}		
					}
					
					base64 = canvas.toDataURL("image/jpeg".0.8);
				}
				//uploadImage(base64);
				$("#myImage").attr("src", base64); }; }; oReader.readAsDataURL(file); }}// Add by LZK
function rotateImg(img, direction,canvas) {  
		//alert(img);
        // Rotate the image 4 times and return to the original direction
        var min_step = 0;  
        var max_step = 3;  
        //var img = document.getElementById(pid);  
        if (img == null)return;  
        // The img height and width cannot be obtained after the IMG element is hidden, otherwise an error will occur
        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++;  
            // Rotate to the original position, i.e. exceed the maximum value
            step > max_step && (step = min_step);  
        } else {  
            step--;  
            step < min_step && (step = max_step);  
        }  
        //img.setAttribute('step', step);  
        /*var canvas = document.getElementById('pic_' + pid); if (canvas == null) { img.style.display = 'none'; canvas = document.createElement('canvas'); canvas.setAttribute('id', 'pic_' + pid); img.parentNode.appendChild(canvas); } * /
        // The rotation Angle takes radians as parameters
        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; }}Copy the code