const file = files[0]// 修正图片旋转
fixImageOrientation(file).then(file2 => {
// 创建预览图片
document.querySelector('img').src = window.URL.createObjectURL(file2)
// 压缩
return compressImage(file2)
}).then(file3 => {
// 更新预览图片
document.querySelector('img').src = window.URL.createObjectURL(file3)
// 上传
return uploadFile(file3)
}).then(data => {
console.log('上传成功')
}).catch(error => {
console.error('上传失败')
})
}
H5 提供了处理文件的接口,借助画布可以在浏览器中实现复杂的图片处理,本文总结了移动端 H5 上传图片这个场景下的一些图片处理实践,以后遇到类似的需求可作为部分参考。
附小程序实现参考
// 拍照
wx.chooseImage({
sourceType: ["camera"],
success: ({ tempFiles }) => {
const file = tempFiles[0]// 处理图片
}
});
/**
* 压缩图片
* @param {Object} params
* filePath: String 输入的图片路径
* success: Function 压缩成功时回调,并返回压缩后的新图片路径
* fail: Function 压缩失败时回调
*/
compressImage({ filePath, success, fail }) {
// 获取图片宽高
wx.getImageInfo({
src: filePath,
success: ({ width, height }) => {
const systemInfo = wx.getSystemInfoSync();
const canvasWidth = systemInfo.screenWidth;
const canvasHeight = systemInfo.screenHeight;
// 更新画布尺寸
this.setData({ canvasWidth, canvasHeight })
// 计算缩放比例
const scaleX = canvasWidth / width;
const scaleY = canvasHeight / height;
const scale = Math.min(scaleX, scaleY);
const imageWidth = width * scale;
const imageHeight = height * scale;
// 将缩放后的图片绘制到画布
const ctx = wx.createCanvasContext("hidden-canvas");
let dx = (canvasWidth - imageWidth) / 2;
let dy = (canvasHeight - imageHeight) / 2;
ctx.drawImage(filePath, dx, dy, imageWidth, imageHeight);
ctx.draw(false, () => {
// 导出压缩后的图片到临时文件
wx.canvasToTempFilePath({
canvasId: "hidden-canvas",
width: canvasWidth,
height: canvasHeight,
destWidth: canvasWidth,
destHeight: canvasHeight,
fileType: "jpg",
quality: 0.92,
success: ({ tempFilePath }) => {
// 隐藏画布
this.setData({ canvasWidth: 0, canvasHeight: 0 })
// 压缩完成
success({ tempFilePath });
},
fail: error => {
// 隐藏画布
this.setData({ canvasWidth: 0, canvasHeight: 0 })
fail(error);
}
});
});
},
fail: error => {
fail(error);
}
});
}
/**
* 上传文件
*/
uploadFile({ uploadUrl, filePath, onData, onError }) {
wx.uploadFile({
url: uploadUrl
filePath: filePath,









