UniApp 压缩图片

2022-07-01  本文已影响0人  CentForever

图片压缩不支持H5

image.png

获取文件path

image.png

文件压缩尝试

squoosh

测试 网站https://squoosh.app/
github地址:https://github.com/GoogleChromeLabs/squoosh

代码

import { ImagePool } from "@squoosh/lib";
import fs from "fs/promises";

async function runSquoosh(imagePath, filename, outputFolderPath) {
  const imagePool = new ImagePool();
  const image = await imagePool.ingestImage(imagePath);
  const preprocessOptions = {
    resize: {
      width: 100,
    },
  };
  await image.preprocess(preprocessOptions);
  const encodeOptions = {
    mozjpeg: {}, //an empty object means 'use default settings'
    jxl: {
      quality: 90,
    },
  };
  await image.encode(encodeOptions);
  const { extension, binary } = await image.encodedWith.mozjpeg;
  fs.writeFileSync(`${outputFolderPath}/${filename}.${extension}`, binary);
  imagePool.close();
}

测试结果

12:24:14.402 文件查找失败:'fs/promises' at utils/squoosh.js:2
12:24:14.402 文件查找失败:'perf_hooks' at node_modules/@squoosh/lib/build/avif_node_enc_mt-143090b9.js:1
12:24:14.408 文件查找失败:'worker_threads' at node_modules/@squoosh/lib/build/index.js:1

疑问:

Canvas

api

uni.createCanvasContext(canvasId, this)
https://uniapp.dcloud.io/api/canvas/createCanvasContext.html#%E5%AE%9A%E4%B9%89
uni.canvasToTempFilePath(object, component)
https://uniapp.dcloud.io/api/canvas/canvasToTempFilePath.html#canvastotempfilepath

注意⚠️

image.png

测试代码

<template>
  <view class="content">
    <view @click="chooseImage"> 选择图片 </view>
    <text>
      {{ path }}
    </text>
    <image :src="path" />
    <view @click="压缩图片;"> 压缩图片 </view>
    <text>
      {{ pathSquoosh }}
    </text>
    <canvas canvas-id="canvas" v-if="show"></canvas>
  </view>
</template>

<script>
//import squoosh from "@/utils/squoosh.js"
export default {
  data() {
    return {
      show: true,
      path: "test",
      pathSquoosh: "test",
    };
  },
  methods: {
    getCanvasImage(canvasId, imagePath, imageW, imageH, getImgsuccess) {
      console.error(`getCanvasImage begin`);
      const that = this;
      const ctx = uni.createCanvasContext(canvasId, that);
      ctx.drawImage(imagePath, 0, 0, imageW, imageH);
      ctx.draw(
        false,
        setTimeout(function () {
          console.error(`getCanvasImage setTimeout`);
          uni.canvasToTempFilePath(
            {
              canvasId: canvasId,
              x: 0,
              y: 0,
              width: imageW,
              height: imageH,
              quality: 1,
              success: function (res) {
                console.log(res.tempFilePath);
                console.error(
                  `getCanvasImage tempFilePath:${res.tempFilePath}`
                );
                getImgsuccess(res.tempFilePath);
              },
              fail(err) {
                console.error(`getCanvasImage fail:${err}`);
              },
              complete() {
                console.error(`getCanvasImage complete`);
              },
            },
            that
          );
          debugger;
        }, 2000)
      );
      console.error(`getCanvasImage wait`);
    },
    chooseImage: function () {
      const that = this;
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图,默认二者都有
        success: function (res) {
          const fileName = res.tempFiles[0].name;
          uni.getImageInfo({
            src: res.tempFilePaths[0],
            success: function (image) {
              console.log(image.width);
              console.log(image.height);
              const maxSide = Math.max(image.width, image.height);
              // 画板的宽高默认是windowWidth
              const windowWH = 120;
              let scale = 1;
              if (maxSide > windowWH) {
                scale = windowWH / maxSide;
              }
              const imageW = Math.trunc(image.width * scale);
              const imageH = Math.trunc(image.height * scale);
              that.getCanvasImage(
                "canvas",
                res.tempFilePaths[0],
                imageW,
                imageH,
                (pressImgPath) => {
                  console.error(`getCanvasImage CallBack:${pressImgPath}`);
                }
              );
            },
          });
          that.path = res.tempFilePaths[0];
          console.log(JSON.stringify(res.tempFilePaths));
          var ready = new FileReader();
          ready.readAsDataURL(res.tempFiles[0]);
          ready.onload = function () {
            var fileResult = this.result;
            console.log(JSON.stringify(fileResult));
          };
          /*uni.getFileSystemManager().readFile({
            filePath: path, //参数path:图片相对路径
            encoding: "base64",
            success: (res) => {
              let base64 = res.data;
              console.log(JSON.stringify(base64));
            },
            fail: (err) => {
              console.log(err);
            },
          });*/
        },
      });
    },
  },
};
</script>
.content { display: flex; flex-direction: column; align-items: center;
justify-content: center; }
<style></style>

测试结果

image.png
LeakCannary检测机制.jpeg

对比

上一篇 下一篇

猜你喜欢

热点阅读