微信小程式根據本地快取圖片路徑,生成縮圖的方法

怪咖咖發表於2024-08-24
公共方法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)

相關文章