作者:小野鲜
链接:https://juejin.cn/post/7535862781671342134
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
链接:https://juejin.cn/post/7535862781671342134
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
在 uni-app 开发中,图片压缩是提升用户体验和优化性能的重要手段。本文提供了一种 兼容 H5 和 App 端的图片压缩方法,在 App 端使用 uni.compressImage 进行高效压缩,而在 H5 端利用 canvas 进行图片缩放压缩,并 支持跨域处理。文章不仅优化了 toDataURL 生成 JPEG 以减少文件大小,还修正了 clearRect 误用问题,并添加了错误处理机制,确保代码在各种情况下都能稳定运行。适用于 uni-app 全平台开发
export const imageCompress = (url) => {
return new Promise((resolve, reject) => {
// #ifndef H5
uni.compressImage({
src: url,
quality: 80, // 压缩质量,范围0~100,仅对 JPG 有效
success: res => {
console.log('app端图片压缩成功:', res.tempFilePath);
resolve(res.tempFilePath);
},
fail: err => {
console.error('app端图片压缩失败:', err);
reject(err);
}
});
// #endif
// #ifdef H5
const img = new Image();
img.crossOrigin = "Anonymous"; // 处理跨域问题
img.src = url;
img.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
let cw = img.width;
let ch = img.height;
let w = cw;
let h = ch;
// 限制最大宽高 600px
if (cw > 600 || ch > 600) {
if (cw > ch) {
w = 600;
h = (600 * ch) / cw;
} else {
h = 600;
w = (600 * cw) / ch;
}
}
canvas.width = w;
canvas.height = h;
context.clearRect(0, 0, w, h);
context.drawImage(img, 0, 0, w, h);
// 输出压缩后的 base64 图片(jpeg 格式,80% 质量)
const base64 = canvas.toDataURL('image/jpeg', 0.8);
resolve(base64);
};
img.onerror = err => {
console.error("H5端图片加载失败:", err);
reject(err);
};
// #endif
});
};
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容