复制代码const upload= async (opt) => {
let maxWidth = 500;
opt = opt || {};
opt.url = opt.url || '';
opt.success = opt.success || function(){ };
console.log(opt.url)
let Orientation = 1;
await getImageTag(opt.url, 'Orientation', function(e) {
if(e != undefined) Orientation = e;
})
var img = null;
var canvas = null;
await comprossImage(opt.url, maxWidth, function(e) {
img = e.img;
canvas = e.canvas;
})
console.log(Orientation)
let baseStr = '';
switch(Orientation){
case 6:
console.log('(向右)90度旋转');
baseStr = rotateImg(img,'right',canvas);
break;
case 8:
console.log('向左)90度旋转');
baseStr = rotateImg(img,'left',canvas);
break;
case 3:
console.log('需要180度旋转');
baseStr = rotateImg(img,'right',canvas, 2);
break;
default:
baseStr = rotateImg(img,'',canvas);
break;
}
opt.success(baseStr); }
const comprossImage = async (imgSrc, maxWidth, func) => {
if(!imgSrc) return 0;
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: imgSrc,
success(res) {
let img = new Image();
img.src = res.path;
console.log(img)
let canvas = document.createElement('canvas');
let obj = new Object();
obj.img = img;
obj.canvas = canvas;
resolve(func(obj));
}
});
})
}
const getImageTag = (file, tag, suc) => {
if (!file) return 0;
return new Promise((resolve, reject) => {
let imgObj = new Image()
imgObj.src = file
console.log(imgObj)
uni.getImageInfo({
src: file,
success(res) {
Exif.getData(imgObj, function () {
Exif.getAllTags(this);
let or = Exif.getTag(this,'Orientation');
resolve(suc(or))
});
}
})
});
};
const rotateImg = (img, direction, canvas, times = 1) => {
console.log('开始旋转')
var min_step = 0;
var max_step = 3;
if (img == null)return;
var height = img.height;
var width = img.width;
let maxWidth = 500;
let canvasWidth = width;
let canvasHeight = height;
let base = canvasWidth/canvasHeight;
console.log(maxWidth);
if(canvasWidth > maxWidth){
canvasWidth = maxWidth;
canvasHeight = Math.floor(canvasWidth/base);
}
width = canvasWidth;
height = canvasHeight;
var step = 0;
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step += times;
step > max_step && (step = min_step);
} else if(direction == 'left'){
step -= times;
step < min_step && (step = max_step);
} else {
step = 0;
}
var degree = step * 90 * Math.PI / 180;
var ctx = canvas.getContext('2d');
console.log(degree)
console.log(step)
switch (step) {
case 1:
console.log('右旋转 90度')
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height, width, height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height, width, height);
break;
case 3:
console.log('左旋转 90度')
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0, width, height);
break;
default:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
break;
}
let baseStr = canvas.toDataURL("image/jpeg", 1);
return baseStr;
}