gpt4 book ai didi

javascript - 通过手机加载时, Canvas 图像将图像旋转 90 度

转载 作者:太空狗 更新时间:2023-10-29 16:39:49 25 4
gpt4 key购买 nike

我正在尝试制作一个小 Canvas 功能,它可以让您上传图片并在其上添加叠加层。我可以上传,在顶部创建图像并下载,但是当我尝试通过手机上传图像时。它将图像旋转 90 度。

我是不是漏掉了什么?在将图像添加到 Canvas 之前,我是否必须测试图像的大小并对其进行缩放?

任何帮助都会有很大的帮助,谢谢。

  <style>
.box{
width: 300px;
height: 300px;
border: 1px solid blue;
padding: 1em;
}
.wrap{
width: 180px;
height: 180px;
margin: 0 auto;
background: red;
position: relative;
}
</style>
<div class="box">
<div class="wrap">
<canvas id="canvas" width="180" height="180"></canvas>
</div>
<br />
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<br />
<br />
<a href="#" clss="buttonLink" id="downloadLink">Download!</a>
</div>
<script>


$(document).ready(function() {
//upload images.
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
//draw image.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//download link.
var downloadLink = document.getElementById('downloadLink');

//upload image.
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){


var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');

var width = 180;
var height = 180;
img.onload = function(){

context.drawImage(img,0,0, width, height);
var imageObj = new Image();
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = icon.png';
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
};
//download link.
downloadLink.onclick = function () {
downloadLink.href = canvas.toDataURL();
downloadLink.download = 'facebook';
};
});
</script>

最佳答案

您需要读取 EXIF 数据并采取相应措施。读取数据的示例库: https://github.com/exif-js/exif-js

也已经回答了问题 JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

同样来自另一个来源,这是你应该如何处理 Canvas 上的 exif 方向:

switch(orientation){
case 2:
// horizontal flip
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180° rotate left
ctx.translate(canvas.width, canvas.height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, canvas.height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90° rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -canvas.height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(canvas.width, -canvas.height);
ctx.scale(-1, 1);
break;
case 8:
// 90° rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-canvas.width, 0);
break;
}

关于javascript - 通过手机加载时, Canvas 图像将图像旋转 90 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35304128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com