html
<input style="border:0" type="file" id="upload1" accept="image/*" οnchange="compress(this);">
//压缩图片
function compress(ele) {var self = ele;
var fileName = $(ele).attr("name");
var file = self.files[0];
var r = new FileReader();
r.readAsDataURL(file);
$(r).load(function () {
var fileStream = ele.result;//base64图片流
var URL = window.URL || window.webkitURL,
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
if (URL && file && ctx) {
var fileURL = URL.createObjectURL(file),
img = new Image();
img.src = fileURL;
img.onload = function () {
var orientation=null;
EXIF.getData(img, function () {
EXIF.getAllTags(this);
orientation = EXIF.getTag(this, "Orientation");// 获取方向角
var degree = 0, drawWidth = img.width, drawHeight = img.height, width, height;
//以下改变一下图片大小
var maxSide = Math.max(drawWidth, drawHeight);
var tarSize = 1024;
if (maxSide > tarSize) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = minSide / maxSide * tarSize;
maxSide = tarSize;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}
canvas.width = width = drawWidth;
canvas.height = height = drawHeight;
switch (orientation) {//横屏竖屏转化
//横屏拍摄,此时home键在左侧
case 3:
degree = 180;
drawWidth = -width;
drawHeight = -height;
break;
//竖屏拍摄,此时home键在下方(正常拿手机的方向)
case 6:
canvas.width = height;
canvas.height = width;
degree = 90;
drawWidth = width;
drawHeight = -height;
break;
//竖屏拍摄,此时home键在上方
case 8:
canvas.width = height;
canvas.height = width;
degree = 270;
drawWidth = -width;
drawHeight = height;
break;
}
//使用canvas旋转校正
ctx.rotate(degree* Math.PI/180);
ctx.drawImage(img, 0, 0, drawWidth, drawHeight);
var base64 = canvas.toDataURL('image/jpeg',1);
var reader = new FileReader();
reader.readAsDataURL(ele.files[0]);
reader.onload = function(e){
$("."+ele.id).attr("src",e.target.result);
$("#"+ele.id+"z").val(base64);
};
canvas = null;
- img = null;
}
} else {
var reader = new FileReader();
reader.readAsDataURL(ele.files[0]);
reader.onload = function(e){
$("."+ele.id).attr("src",e.target.result);
$("#"+ele.id+"z").val(e.target.result);
};
}
});
}
或参照 http://www.jb51.net/article/78732.htm