jquery 手机端上传图片

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery 手机端上传图片相关的知识,希望对你有一定的参考价值。

需要引入exif.js,矫正iphone拍摄图片方向

function readImage(file) {
if (!/image\/\w+/.test(file.type)) {
alert(“上传图片格式不支持”);
return false;
}
var Orientation = null;
// var URL = URL || webkitURL;
//获取照片方向角属性,用户旋转控制
EXIF.getData(file, function () {
// alert(EXIF.pretty(this));
EXIF.getAllTags(this);
//alert(EXIF.getTag(this, ‘Orientation‘));
Orientation = EXIF.getTag(this, ‘Orientation‘);
//return;
});

var reader = new FileReader();
reader.onload = function (e) {
//if (navigator.userAgent.match(/iphone/i)) {
// // //如果方向角不为1,都需要进行旋转 added by lzk
// if (Orientation != "" && Orientation != 1) {
getImgData(this.result, Orientation, function (data_url) {
//这里可以使用校正后的图片data了
$("#ID" ).attr("src", data_url);

});
// }
//}
}
reader.readAsDataURL(file);

}

 

// @param {string} img 图片的base64
// @param {int} dir exif获取的方向信息
// @param {function} next 回调方法,返回校正方向后的base64
function getImgData(img, dir, next) {
var image = new Image();
image.onload = function () {
var degree = 0, drawWidth, drawHeight, width, height;
drawWidth = this.naturalWidth;
drawHeight = this.naturalHeight;
//以下改变一下图片大小
//var maxSide = Math.max(drawWidth, drawHeight);
//if (maxSide > 1024) {
// var minSide = Math.min(drawWidth, drawHeight);
// minSide = minSide / maxSide * 1024;
// maxSide = 1024;
// if (drawWidth > drawHeight) {
// drawWidth = maxSide;
// drawHeight = minSide;
// } else {
// drawWidth = minSide;
// drawHeight = maxSide;
// }
//}
//以下改变一下图片大小
var maxSide = Math.max(drawWidth, drawHeight);
if (maxSide > 640) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = minSide / maxSide * 640;
maxSide = 640;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}

var canvas = document.createElement(‘canvas‘);
canvas.width = width = drawWidth;
canvas.height = height = drawHeight;
var context = canvas.getContext(‘2d‘);
//判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
switch (dir) {

//iphone横屏拍摄,此时home键在左侧
case 3:
degree = 180;
drawWidth = -width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
case 6:
canvas.width = height;
canvas.height = width;
degree = 90;
drawWidth = width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在上方
case 8:
canvas.width = height;
canvas.height = width;
degree = 270;
drawWidth = -width;
drawHeight = height;
break;
}

//使用canvas旋转校正
context.rotate(degree * Math.PI / 180);
context.drawImage(this, 0, 0, drawWidth, drawHeight);
//返回校正图片
next(canvas.toDataURL("image/jpeg", 0.8));//压缩率
}
image.src = img;
}

 


































































































以上是关于jquery 手机端上传图片的主要内容,如果未能解决你的问题,请参考以下文章

H5+jqweui实现手机端图片压缩上传

手机上传图片的一些小问题

纯原生js移动端图片压缩上传插件

移动端图片裁剪上传—jQuery.cropper.js

Exif.js获取图片的详细信息(苹果手机移动端上传图片旋转90度)

手机端上传相册图片