旋转压缩部分因为有文件的不同类型相互转换,所以方法调用比较多,看起来有点乱,但是实际不难理解,建议粘贴到编辑器比较方便看,希望此文章对大家有帮助
1.依赖 jquery.js
2.html部分
//capture="camera" 设置手机端打开上传文件时使用手机摄像头拍照上传,不写则默认拍照或相册
3.js部分
$('.addImage').on('change',function(){
//开始处理图片,此时可以做一些“图片上传中。。。”的提示等
var fileObj = this.files[0];
var fileName = fileObj.name;
//压缩,先旋转在压缩,因为cavers从画图压缩,压缩后的图片就没有角度等信息了
photoCompress(fileObj, {
quality: 0.2 //清晰度
}, function(base64Codes){
//旋转并且压缩后传回base64编码,此时可以用ajax与后端传输图片,此方法不做演示
//模拟表单提交
var form = new FormData(); // FormData 对象
var bl = convertBase64ToBlob(base64Codes); //base64转化为blob对象
form.append("loadFile", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件对象
xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
xhr.open("post","<../medicalAppointment/tempImg.do", true);
//xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】
//请求完成执行uploadComplete
xhr.onload = function uploadComplete(evt){
var data = evt.target.responseText; //返回的数据data
console.log(data)
};
xhr.onerror = function uploadFailed(){}; //请求失败
xhr.send(form); //开始上传,发送form数据
})
})
//压缩后base64转化为blob
var convertBase64ToBlob = function(base64){
var base64Arr = base64.split(',');
var imgtype = '';
var base64String = '';
if(base64Arr.length > 1){
//如果是图片base64,去掉头信息
base64String = base64Arr[1];
imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':')+1,base64Arr[0].indexOf(';'));
}
// 将base64解码
var bytes = atob(base64String);
//var bytes = base64;
var bytesCode = new ArrayBuffer(bytes.length);
// 转换为类型化数组
var byteArray = new Uint8Array(bytesCode);
// 将base64转换为ascii码
for (var i = 0; i < bytes.length; i++) {
byteArray[i] = bytes.charCodeAt(i);
}
// 生成Blob对象(文件对象)
return new Blob( [bytesCode] , {type : imgtype});
};
//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//判断手机类型安卓/ios
function isAndroid_ios(){
var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
return isAndroid==true?true:false;
}
//压缩图片
function photoCompress(file,w,objDiv){
var ready=new FileReader();
/*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
ready.readAsDataURL(file);
ready.onload=function(){
var re=this.result;
var imageSize = e.total;//图片大小
if(isAndroid_ios()){
//安卓 //不旋转图片
canvasDataURL(re,w,objDiv)
}else{
//旋转图片
var image = new Image();
image.src = re;
image.onload = function () {
//开始旋转图片
var newImage = rotateImage(image);
var newImageSrc = newImage.src;
canvasDataURL(newImageSrc,w,objDiv);
}
}
}
}
function canvasDataURL(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 图片原始尺寸
var originWidth = that.width;
var originHeight = that.height;
// 最大尺寸限制,可通过设置宽高来实现图片压缩程度
var maxWidth = 1000,
maxHeight = 2000;
// 目标尺寸
var w = originWidth || obj.width,
h = originHeight || obj.height;
// 图片尺寸超过1000x2000的限制
if(originWidth > maxWidth || originHeight > maxHeight) {
if(originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
w = maxWidth;
h = Math.round(maxWidth * (originHeight / originWidth));
} else {
h = maxHeight;
w = Math.round(maxHeight * (originWidth / originHeight));
}
}
// 默认按比例压缩
/* var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);*/
var quality = 0.7; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}
//旋转图片,手机拍照上传图片旋转问题
function rotateImage(image) {
//console.log('rotateImage');
var width = image.width;
var height = image.height;
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d');
var newImage = new Image();
//旋转图片操作
EXIF.getData(image,function () {
var orientation = EXIF.getTag(this,'Orientation');
// orientation = 6;//测试数据
//alert('orientation:'+orientation);
switch (orientation){
//正常状态
case 1:
console.log('旋转0°');
// canvas.height = height;
// canvas.width = width;
newImage = image;
break;
//旋转90度
case 6:
console.log('旋转90°');
canvas.height = width;
canvas.width = height;
ctx.rotate(Math.PI/2);
ctx.translate(0,-height);
ctx.drawImage(image,0,0);
imageDate = canvas.toDataURL('Image/jpeg',1)
newImage.src = imageDate;
break;
//旋转180°
case 3:
console.log('旋转180°');
canvas.height = height;
canvas.width = width;
ctx.rotate(Math.PI);
ctx.translate(-width,-height);
ctx.drawImage(image,0,0);
imageDate = canvas.toDataURL('Image/jpeg',1)
newImage.src = imageDate;
break;
//旋转270°
case 8:
console.log('旋转270°');
canvas.height = width;
canvas.width = height;
ctx.rotate(-Math.PI/2);
ctx.translate(-height,0);
ctx.drawImage(image,0,0);
imageDate = canvas.toDataURL('Image/jpeg',1)
newImage.src = imageDate;
break;
//undefined时不旋转
case undefined:
console.log('undefined 不旋转');
newImage = image;
break;
}
}
);
return newImage;
}