前端判断ios图片是否旋转,需要在页面中引用exif.js
<script type="text/javascript" src="js/exif.js" ></script>
在vue中使用
npm install exif.js
import EXIF from 'exif-js'
// 挂载到vue实例中
Vue.prototype.Exif = EXIF
// 通过base64来判断图片大小
function getImgSize(base64url) {
//获取base64图片大小,返回KB数字
var str = base64url.replace('data:image/jpeg;base64,', '');//这里根据自己上传图片的格式进行相应修改
var strLength = str.length;
var fileLength = parseInt(strLength - (strLength / 8) * 2)
// 由字节转换为KB
var size = (fileLength / 1024).toFixed(2)
return parseInt(size)
}
// 生成base64图片
export function base64 (selector, targetSize = 3956) {
return new Promise(resolve => {
var oFReader = new FileReader()
var file = document.getElementById(selector).files[0]
let size = file.size / 1024, Orientation = null
EXIF.getData(file, function(){
Orientation = EXIF.getTag(this, 'Orientation');
})
loading = weui.loading()
oFReader.readAsDataURL(file)
oFReader.onloadend = function(oFRevent){
if (size <= targetSize) {
resolve(oFRevent.target.result)
loading.hide()
} else {
var img = new Image()
img.src = oFRevent.target.result
if (img.complete) {
callback()
} else {
img.onload = callback
}
function callback() {
resolve(compressImg(img, Orientation, targetSize))
img = null
}
}
}
})
}
// 压缩图片
function compressImg (img, Orientation, targetSize) {
let canvas = document.createElement("canvas")
let ctx = canvas.getContext('2d')
let width = img.width
let height = img.height
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
let ratio;
if ((ratio = width * height / 3500000) > 1) {
ratio = Math.sqrt(ratio)
width /= ratio
height /= ratio
} else {
ratio = 1
}
canvas.width = width;
canvas.height = height;
//铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (Orientation == 3) {
canvas.width = width;
canvas.height = height;
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, -width, -height)
} else if (Orientation == 8) {
canvas.width = height;
canvas.height = width;
ctx.rotate(Math.PI * 3 / 2);
ctx.drawImage(img, 0, 0, -width, height)
} else if (Orientation == 6) {
canvas.width = height;
canvas.height = width;
ctx.rotate(Math.PI / 2);
ctx.drawImage(img, 0, 0, width, -height)
} else {
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height)
}
// 循环压缩至100k左右
let quality = 1.05, ndata = ''
do {
quality -= 0.05
ndata = canvas.toDataURL('image/jpeg', quality)
} while (getImgSize(ndata) > targetSize)
loading.hide()
return ndata
}
使用示例:
// dom
<input id="inputCamera" @change="cameraImg" type="file" accept="image/*" capture="camera" />
//js
base64('inputCamera1').then(res => {
console.log(res)
})