import EXIF from 'exif-js'
* 使用二进制方式处理dataUrl
* @param {*} dataUrl
*/
const convertBase64UrlToBlob = (dataUrl, callback) => {
const binaryString = window.atob(dataUrl.split(',')[1])
const arrayBuffer = binaryString.length
const intArray = new Uint8Array(arrayBuffer)
const imgType = dataUrl.match(/data:([^;]+)/)[1]
for (let i = 0, j = arrayBuffer; i < j; i++) {
intArray[i] = binaryString.charCodeAt(i)
}
const data = [intArray]
let blob = new Blob(data, {type: imgType})
callback(blob)
}
* 修复某些机型出现旋转的问题
* @param {*} img
* @param {*} canvas
* @param {*} imgWidth
* @param {*} imgHeight
*/
const fixOrientation = (img, canvas, imgWidth, imgHeight) => {
let orientation
let ctx = canvas.getContext('2d')
EXIF.getData(img, function() {
orientation = EXIF.getTag(this, 'Orientation')
})
if(orientation && orientation != 1){
switch(orientation){
case 6:
canvas.width = imgHeight
canvas.height = imgWidth
ctx.rotate(Math.PI / 2)
ctx.drawImage(img, 0, -imgHeight, imgWidth, imgHeight)
break
case 3:
ctx.rotate(Math.PI);
ctx.drawImage(img, -imgWidth, -imgHeight, imgWidth, imgHeight)
break
case 8:
canvas.width = imgHeight
canvas.height = imgWidth
ctx.rotate(3 * Math.PI / 2)
ctx.drawImage(img, -imgWidth, 0, imgWidth, imgHeight)
break
}
}
else{
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
}
}
* 使用canvas绘制图片并压缩
* @param {*} dataUrl 转换的二进制
* @param {*} imgType 图片类型
* @param {*} quality 图片压缩的比例
*/
const canvasDataURL = (dataUrl, imgType, quality = 0.8, callback) => {
let img = new Image()
let compressedDataUrl
img.src = dataUrl
img.onload = function(){
let w = this.width
let h = this.height
let canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
fixOrientation(this, canvas, w, h)
compressedDataUrl = canvas.toDataURL(imgType, Number(quality))
convertBase64UrlToBlob(compressedDataUrl, callback)
}
}
export const compressImg = (file, maxSize, callback) => {
const imgType = file.type || 'image/jpeg'
const ready = new FileReader()
ready.readAsDataURL(file)
ready.onload = function(e){
const { result } = e.target
const quality = ( maxSize / result.length).toFixed(2)
canvasDataURL(result, imgType, quality <= 1 ? quality : 1, callback)
}
}