export default async function imgCompress(fileObj,quality) {
return new Promise((resolve, reject) => {
try {
const image = new Image()
image.src = URL.createObjectURL(fileObj)
image.onload = function() {
const that = this
// 默认按比例压缩
let w = that.width
let h = that.height
const scale = w / h
w = fileObj.width || w
h = fileObj.height || (w / scale)
// 生成canvas
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 创建属性节点
const anw = document.createAttribute('width')
anw.nodeValue = w
const anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(that, 0, 0, w, h)
// quality值越小,所绘制出的图像越模糊
const data = canvas.toDataURL('image/jpeg', quality)
// 压缩完成执行回调
const newFile = base64toFile(data)
resolve(newFile)
}
} catch (e) {}
})
}
function base64toFile(base, filename) {
var arr = base.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var suffix = mime.split("/")[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
//转换成file对象
return new File([u8arr], `filename.${suffix}`, {
type: mime
});
}
uniapp js上传图片压缩
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 之前我发表一篇文章,vue.js 上传图片,可解决平时应用场景的问题,但对复杂的图片处理问题,比如:图片裁剪、压缩...
- 转载至https://www.jianshu.com/p/66bf30c2a778[https://www.jia...
- 大家好,我是云皓,话不多说,直入正题 1,获取input上传file文件2,转化为base64文件3,压缩4,转换...