123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- // 压缩上传图片
- export function translate(imgSrc, scale, fileName, callback) {
- let scales = parseFloat(scale.toFixed(2))
- let img = new Image();
- img.src = imgSrc;
- img.onload = function() {
- let canvas = document.createElement('canvas') // 创建Canvas对象(画布)
- const context = canvas.getContext('2d')
- // 默认按比例压缩
- // let cw = img.width
- // let ch = img.height
- let w = img.width
- let h = img.height
- canvas.width = w
- canvas.height = h
- // if (cw > 600 && cw > ch) {
- // w = 600
- // h = (600 * ch) / cw
- // canvas.width = w
- // canvas.height = h
- // }
- // if (ch > 600 && ch > cw) {
- // h = 600
- // w = (600 * cw) / ch
- // canvas.width = w
- // canvas.height = h
- // }
- // 生成canvas
- context.clearRect(0, 0, 0, w, h)
- context.drawImage(img, 0, 0, w, h)
- let dataurl = canvas.toDataURL('image/jpeg', scales); //压缩比例
- let arr = dataurl.split(',')
- // console.log(arr, dataurl, 'translate')sss
- let mime = arr[0].match(/:(.*?);/)[1]
- let bstr = atob(arr[1])
- let n = bstr.length
- let 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);
- }
- }
|