|
|
@@ -0,0 +1,38 @@ |
|
|
|
// 压缩上传图片 |
|
|
|
export function translate(imgSrc, scale, fileName, callback) { |
|
|
|
let img = new Image(); |
|
|
|
img.src = imgSrc; |
|
|
|
img.onload = function() { |
|
|
|
let that = this; |
|
|
|
let h = that.height * 0.8; // 默认按比例压缩 |
|
|
|
let w = that.width * 0.8; |
|
|
|
let canvas = document.createElement('canvas'); |
|
|
|
let ctx = canvas.getContext('2d'); |
|
|
|
let width = document.createAttribute("width"); |
|
|
|
width.nodeValue = w; |
|
|
|
let height = document.createAttribute("height"); |
|
|
|
height.nodeValue = h; |
|
|
|
canvas.setAttributeNode(width); |
|
|
|
canvas.setAttributeNode(height); |
|
|
|
ctx.drawImage(that, 0, 0, w, h); |
|
|
|
// 设置边框样式 |
|
|
|
ctx.strokeStyle = '#fff'; |
|
|
|
ctx.lineWidth = 5; |
|
|
|
ctx.strokeRect(0, 0, w, h); |
|
|
|
let dataurl = canvas.toDataURL('image/jpeg', scale); //压缩比例 |
|
|
|
let arr = dataurl.split(','), |
|
|
|
mime = arr[0].match(/:(.*?);/)[1], |
|
|
|
bstr = atob(arr[1]), |
|
|
|
n = bstr.length, |
|
|
|
u8arr = new Uint8Array(n); |
|
|
|
while (n--) { |
|
|
|
u8arr[n] = bstr.charCodeAt(n); |
|
|
|
} |
|
|
|
let file = new File([u8arr], fileName, { |
|
|
|
type: mime |
|
|
|
}); |
|
|
|
// file.lastModifiedDate = new Date(); |
|
|
|
canvas = null; |
|
|
|
callback && callback(dataurl, file); |
|
|
|
} |
|
|
|
} |