最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

uni-app小程序項目中實現前端圖片壓縮實現方式(附詳細代碼)

 更新時間:2025年09月24日 11:04:57   作者:柑橘烏云_  
在uni-app開發(fā)中,文件上傳和圖片處理是很常見的需求,但也經常會遇到各種問題,下面這篇文章主要介紹了uni-app小程序項目中實現前端圖片壓縮實現方式的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

方式一:使用<canvas>實現圖片壓縮(推薦,兼容性好)

這是最常見的一種方式,通過將圖片繪制到 <canvas> 上,然后用 canvas.toTempFilePathcanvas.toDataURL 得到壓縮后的圖片。

示例代碼(小程序平臺):

<template>
  <view>
    <button @click="chooseImage">選擇圖片并壓縮</button>
  </view>
</template>

<script>
export default {
  methods: {
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.compressImage(tempFilePath);
        }
      });
    },

    compressImage(path) {
      // 創(chuàng)建 canvas 實例
      const ctx = uni.createCanvasContext('myCanvas', this);
      uni.getImageInfo({
        src: path,
        success: (img) => {
          const maxW = 800; // 最大寬度
          const scale = maxW / img.width;
          const w = maxW;
          const h = img.height * scale;

          // 畫圖
          ctx.drawImage(path, 0, 0, w, h);
          ctx.draw(false, () => {
            // 延遲一點,確保畫完
            setTimeout(() => {
              uni.canvasToTempFilePath({
                canvasId: 'myCanvas',
                destWidth: w,
                destHeight: h,
                success: (res) => {
                  console.log('壓縮后圖片路徑:', res.tempFilePath);
                  // 可以用 res.tempFilePath 上傳或預覽
                },
                fail: (err) => {
                  console.error('canvas 轉圖片失敗', err);
                }
              }, this);
            }, 200);
          });
        }
      });
    }
  }
};
</script>

<canvas canvas-id="myCanvas" style="width: 800px; height: 600px;" />

方式二:使用uni.compressImageAPI(簡單但壓縮能力有限)

這是 uni-app 封裝的一個簡單壓縮接口,用于壓縮臨時文件路徑圖片

uni.chooseImage({
  count: 1,
  success: (res) => {
    const filePath = res.tempFilePaths[0];
    uni.compressImage({
      src: filePath,
      quality: 80, // 取值 0 - 100,越小壓縮率越高
      success: (res) => {
        console.log('壓縮成功:', res.tempFilePath);
      },
      fail: (err) => {
        console.error('壓縮失?。?, err);
      }
    });
  }
});

注意:

  • uni.compressImage 目前只支持 App 和微信小程序平臺,在 H5 和其他平臺會失效或無效果。

  • 圖片質量壓縮效果受限,不能調整尺寸。

方式三:使用三方庫(僅 H5 適用,如compressorjs)

這種方式適合在 H5 中運行的 uni-app 項目,小程序端不支持 DOM。

npm install compressorjs
import Compressor from 'compressorjs';

new Compressor(file, {
  quality: 0.6,
  success(result) {
    console.log('壓縮后的 Blob:', result);
    // 你可以用 FileReader 或 FormData 處理這個文件
  },
  error(err) {
    console.error(err.message);
  },
});
方式平臺支持優(yōu)點缺點
Canvas 壓縮? 微信小程序、App自由控制尺寸和質量,通用性強需要一定代碼量
uni.compressImage? 微信小程序、App簡單易用無法控制尺寸,兼容性不夠
compressorjs? 僅 H5封裝好,效果不錯不支持小程序環(huán)境

 最后:封裝公共方法

// utils/compressImage.js

/**
 * 通用圖片壓縮函數(兼容小程序/APP/H5)
 * @param {String} src 原始圖片路徑
 * @param {Object} options 配置項 { quality, width, height }
 * @returns {Promise<String>} 返回壓縮后圖片路徑
 */
export function compressImage(src, options = {}) {
  const { quality = 0.7, width = 800, height = null } = options;

  return new Promise((resolve, reject) => {
    // 判斷運行平臺
    const system = uni.getSystemInfoSync().platform;

    // 優(yōu)先使用 canvas 壓縮
    #ifdef MP-WEIXIN || APP-PLUS
    uni.getImageInfo({
      src,
      success(imgInfo) {
        const ratio = width / imgInfo.width;
        const targetWidth = width;
        const targetHeight = height || imgInfo.height * ratio;

        const canvasId = 'compressCanvas';
        const ctx = uni.createCanvasContext(canvasId);

        ctx.drawImage(src, 0, 0, targetWidth, targetHeight);
        ctx.draw(false, () => {
          setTimeout(() => {
            uni.canvasToTempFilePath({
              canvasId,
              destWidth: targetWidth,
              destHeight: targetHeight,
              fileType: 'jpg',
              quality,
              success(res) {
                resolve(res.tempFilePath);
              },
              fail(err) {
                reject(err);
              }
            });
          }, 200);
        });
      },
      fail: reject
    });
    #endif

    // H5 平臺(用原圖或者 compressorjs)
    #ifdef H5
    // 可以在此擴展 compressorjs 邏輯
    resolve(src); // 默認返回原圖
    #endif
  });
}

總結 

到此這篇關于uni-app小程序項目中實現前端圖片壓縮實現方式的文章就介紹到這了,更多相關uni-app前端圖片壓縮內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

潜江市| 离岛区| 宁南县| 新民市| 扶沟县| 大埔区| 成安县| 深州市| 建宁县| 沙洋县| 通山县| 海林市| 奎屯市| 湟中县| 绥阳县| 长汀县| 远安县| 郸城县| 南京市| 乌兰县| 孟津县| 玉环县| 卢湾区| 久治县| 闽侯县| 抚宁县| 互助| 宾阳县| 来安县| 北京市| 全州县| 布尔津县| 旬邑县| 东乡县| 大邑县| 扎兰屯市| 滦南县| 胶州市| 泸州市| 甘德县| 杭锦旗|