微信小程序根据本地缓存图片路径,生成缩略图的方法
公共方法js文件 /** * 生成缩略图 * @param canvasId canvas容器的id * @param fileUrl 缓存在本地图片的路径 * @param thumbnailRange 期待生成的缩略图尺寸范围,默认150,即宽或高不会超过150px */ function generateThumbnail(canvasId,fileUrl,thumbnailRange=150) { return new Promise((resolve, reject) => { wx.getImageInfo({ src: fileUrl, success: (res) => { const previewImageWidth = res.width; // 原图宽度 const previewImageHeight = res.height; // 原图高度 wx.createSelectorQuery().select(canvasId).fields({ node: true, size: true, }).exec((res) => { const previewImageRatio = previewImageWidth / previewImageHeight; // 原图宽高比例 let thumbnailHeight,thumbnailWidth; if (previewImageRatio > 1) { thumbnailWidth = thumbnailRange; // 缩略图宽度固定为 150 thumbnailHeight = thumbnailWidth / previewImageRatio; } else { thumbnailHeight = thumbnailRange; thumbnailWidth = thumbnailHeight * previewImageRatio; } const canvas = res[0].node; const ctx = canvas.getContext('2d'); const img = canvas.createImage(); canvas.width = thumbnailRange; canvas.height = thumbnailRange; img.src = fileUrl; img.onload = () => { ctx.drawImage(img,0,0,thumbnailWidth,thumbnailHeight); wx.canvasToTempFilePath({ canvas: canvas, x: 0, y: 0, width: thumbnailWidth, height: thumbnailHeight, destWidth: thumbnailWidth, destHeight: thumbnailHeight, success: (res) => { // 解析缩略图的临时路径 resolve(res.tempFilePath); }, fail: (err) => { reject(err); } }); }; img.onerror = (err) => { reject(err); }; }); }, fail: (err) => { reject(err); } }); }); } /** * 将异步生成缩略图所有方法包装成同步方法 * @param canvasId canvas容器的id * @param fileUrl 缓存在本地图片的路径 * @param thumbnailWidth 期待生成的缩略图宽度,默认150 * @param thumbnailHeight 期待生成的缩略图高度,默认150 */ export async function getThumbnailUrl(canvasId,fileUrl,thumbnailRange) { try { const url = await generateThumbnail(canvasId,fileUrl,thumbnailRange); return url; } catch (error) { console.error('生成缩略图失败:', error); return null; } }
wxml代码
<canvas class="original-canvas" canvas-id="originalCanvas" id="originalCanvas" type="2d"></canvas>
js引用公共方法代码
const originalUrl = await getThumbnailUrl('#originalCanvas',file.url,800)