最近在做图片上传,在手机上通过网页 input 标签拍照上传图片,有一些手机会出现图片旋转了90度的问题,也就是本该立着的照片躺着了, 在网上查了一些资料,是拿手机拍照方向的问题
通过获取图片的Orientation值来判断,照片旋转多少度
参数值 | 旋转角度 |
---|---|
1 | 0° |
3 | 180° |
6 | 顺时针90° |
8 | 逆时针90° |
想要获取 Orientation 参数,可以通过 exif.js 库来操作
核心代码如下
var Orientation = null;//图片方向角
//获取照片方向角属性,用户旋转控制
EXIF.getData(file, function () {
EXIF.getAllTags(this);
Orientation = EXIF.getTag(this, 'Orientation');//这个Orientation 就是我们判断需不需要旋转的值了,有1、3、6、8
});
核心代码如下
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
//为6的时候,图片需宽高反转
if (Orientation && Orientation == 6 && img.width > img.height) {
canvas.width = img.height;
canvas.height = img.width;
}
switch (Orientation) {
case 8:// 需要逆时针(向右)90度旋转
ctx.rotate(270 * Math.PI / 180);
ctx.drawImage(img, -img.height, 0, img.height, img.width);
case 3:// 需要180度旋转
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
break;
case 6:// 需要顺时针(向左)90度旋转
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0, 0, img.width, -img.height);
default:
ctx.drawImage(img, 0, 0, img.width, img.height);
break;
}
toDataURL() 方法返回一个包含图片展示的 data URI 。使用两个参数,第一个参数为图片格式,默认为 image/png。第二个参数为压缩质量,在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。toDataURL() 方法返回一个包含图片展示的 data URI 。使用两个参数,第一个参数为图片格式,默认为 image/png。第二个参数为压缩质量,在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。
核心代码如下
var base64 = canvas.toDataURL('image/jpeg',0.8); //0.8指的是压缩80%
核心代码如下
var formData = new FormData();
formData.append("images", base64);
$.ajax({
url: "xxx.php",
type: 'POST',
data: formData,
contentType:false,
processData:false,
success: function(data){},
error: function(xhr, type){}
});
核心代码如下
//接受图片
$logo = Yii::$app->request->post('images');
$base64_image = str_replace(' ', '+', $logo);
//post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)) {
//创建文件夹
$saveOriginPath = date('Ymd/', time());
$uploadPath = \Yii::getAlias('@uploadPath/' . $saveOriginPath);
FileHelper::createDirectory($uploadPath);
//生成图片名
$filename = Yii::$app->getSecurity()->generateRandomString();
if ($result[2] == 'jpeg') {
$imginfo = $filename . '.jpg';
} else {
$imginfo = $filename . "." . $result[2];
}
$image_file = $uploadPath . DIRECTORY_SEPARATOR . $imginfo;
//拼凑路径
$dir = $saveOriginPath . DIRECTORY_SEPARATOR . $imginfo;
//服务器文件存储路径
if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))) {
//$src为文件路径
$src = $dir;
} else {
$src = null;
}
}
return $src;