1.先把base64转化为Blob
function base64ToBlob (urlData) {
var arr = urlData.split(',')
var mime = arr[0].match(/:(.*?);/)[1] || 'image/png'
// 去掉url的头,并转化为byte
var bytes = window.atob(arr[1])
// 处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length)
// 生成视图(直接针对内存):8位无符号整数,长度1个字节
var ia = new Uint8Array(ab)
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i)
}
return new Blob([ab], {
type: mime
})
}
2.使用exif.js获取图片的Orientation信息
function uploadImg (file, scale, callBack) {
let imgBuffer = base64ToBlob(file.content)
console.log(imgBuffer)
console.dir(Exif)
Exif.getData(imgBuffer, function () {
Exif.getAllTags(this)
let Orientation = Exif.getTag(this, 'Orientation') || ''
console.log('Orientation', Orientation)
if (Orientation && Orientation != 1) {
imgManage(file, scale, callBack, Orientation)
} else {
imgManage(file, scale, callBack, Orientation)
}
})
}
3.根据Orientation对图片进行旋转
img.onload = () => {
// 指定canvas画布大小,该大小为最后生成图片的大小
canvas.width = img.width / 4
canvas.height = img.height / 4
let imgHeight = canvas.width
let imgWidth = canvas.height
/* drawImage画布绘制的方法。(0,0)表示以Canvas画布左上角为起点,400,300是将图片按给定的像素进行缩小。
如果不指定缩小的像素图片将以图片原始大小进行绘制,图片像素如果大于画布将会从左上角开始按画布大小部分绘制图片,最后的图片就是张局部图。 */
if (Orientation && Orientation != 1) {
console.log('恢复角度')
switch (Orientation) {
case 6: // 旋转90度
context.rotate(Math.PI / 2)
context.drawImage(img, 0, -imgHeight, imgWidth, imgHeight)
console.log('恢复角度')
break
case 3: // 旋转180度
context.rotate(Math.PI)
context.drawImage(img, -imgWidth, -imgHeight, imgWidth, imgHeight)
break
case 8: // 旋转-90度
canvas.width = imgHeight
canvas.height = imgWidth
context.rotate((3 * Math.PI) / 2)
context.drawImage(img, -imgWidth, 0, imgWidth, imgHeight)
break
}
} else {
context.drawImage(img, 0, 0, canvas.width, canvas.height)
}