# uni.compressImage(options)

压缩图片

# compressImage 兼容性

Web Android iOS
x 4.18 4.25

# 参数

名称 类型 必填 默认值 兼容性 描述
options CompressImageOptions - - -
名称 类型 必备 默认值 兼容性 描述
src string.ImageURIString - - 图片路径,图片的路径,可以是相对路径、临时文件路径、存储文件路径
quality number - - 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)
rotate number - - 旋转度数,范围0~360
compressedHeight number - - 压缩后图片的高度,单位为px,若不填写则默认以compressedWidth为准等比缩放
compressedWidth number - - 压缩后图片的宽度,单位为px,若不填写则默认以compressedHeight为准等比缩放。
success (callback: CompressImageSuccess) => void - - 接口调用成功的回调函数
fail (callback: IMediaError) => void - - 接口调用失败的回调函数
complete (callback: any) => void - - 接口调用结束的回调函数(调用成功、失败都会执行)
height string - - 缩放图片的高度 已废弃
width string - - 缩放图片的宽度 已废弃

# CompressImageSuccess 的属性值

名称 类型 必备 默认值 兼容性 描述
tempFilePath string - - 压缩后图片的临时文件路径

# IMediaError 的属性值

名称 类型 必备 默认值 兼容性 描述
errCode number - - 错误码
合法值 兼容性 描述
1101001 - 用户取消
1101002 - urls至少包含一张图片地址
1101003 - 文件不存在
1101004 - 图片加载失败
1101005 - 未获取权限
1101006 - 图片或视频保存失败
1101007 - 图片裁剪失败
1101008 - 拍照或录像失败
1101009 - 图片压缩失败
1101010 - 其他错误
errSubject string - - 统一错误主题(模块)名称
data any - - 错误信息中包含的数据
cause Error - - 源错误信息,可以包含多个错误,详见SourceError
errMsg string - - -

# 参见

# 示例

hello uni-app x

该 API 不支持 Web,请运行 hello uni-app x 到 App 平台体验

扫码体验(手机浏览器跳转到App直达页)
<template>
  <!-- #ifdef APP -->
  <scroll-view style="flex:1">
  <!-- #endif -->
    <view>
      <page-head :title="title"></page-head>
      <view class="uni-padding-wrap">
        <view class="image-container">
          <image class="image" :src="beforeCompressPath" mode="aspectFit"></image>
          <image class="image" :src="afterCompressPath" mode="aspectFit"></image>
        </view>
        <view class="uni-title">
          <text class="uni-subtitle-text">压缩前图片信息</text>
        </view>
        <text>{{beforeCompressImageInfo}}</text>
        <view class="uni-title">
          <text class="uni-subtitle-text">压缩后图片信息</text>
        </view>
        <text>{{afterCompressImageInfo}}</text>
        <view class="uni-btn-v">
          <button type="primary" @click="chooseImage">从相册中选取待压缩的图片</button>
        </view>
        <view class="uni-btn-v">
          <button type="primary" @click="compressImage">压缩图片</button>
        </view>
      </view>
      <input-data defaultValue="80" title="压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)" type="number"
        @confirm="onQualityConfirm"></input-data>
      <input-data title="压缩后图片的宽度,单位px" type="string" @confirm="onCompressedWidthConfirm"></input-data>
      <input-data title="压缩后图片的高度,单位px" type="string" @confirm="onCompressedHeightConfirm"></input-data>
      <input-data defaultValue="0" title="旋转度数,范围0~360" type="number" @confirm="onRotateConfirm"></input-data>
    </view>
  <!-- #ifdef APP -->
  </scroll-view>
  <!-- #endif -->
</template>

<script>
  // #ifdef APP-ANDROID
  import FileInputStream from 'java.io.FileInputStream';
  // #endif
  export default {
    data() {
      return {
        title: "compressImage",
        beforeCompressImageInfo: "",
        afterCompressImageInfo: "",
        beforeCompressPath: "",
        afterCompressPath: "",
        quality: 80,
        compressedWidth: null as number | null,
        compressedHeight: null as number | null,
        rotate: 0,
        // 自动化测试
        imageInfoForTest: null,
        imageSrcForTest: '/static/test-image/logo.png'
      }
    },
    methods: {
      compressImage() {
        if (this.beforeCompressPath == "") {
          uni.showToast({
            title: "请先选择图片",
            icon: "error"
          });
          return;
        }
        uni.showLoading({
          title: "图片压缩中"
        });
        uni.compressImage({
          src: this.beforeCompressPath,
          quality: this.quality,
          compressedWidth: this.compressedWidth,
          compressedHeight: this.compressedHeight,
          rotate: this.rotate,
          success: (res) => {
            console.log("compressImage success", JSON.stringify(res));
            this.afterCompressPath = res.tempFilePath;
            uni.showToast({
              title: "压缩成功",
              icon: null
            });
            uni.getImageInfo({
              src: res.tempFilePath,
              success: (_res) => {
                this.afterCompressImageInfo = `图片宽度: ${_res.width}\n图片高度: ${_res.height}\n`;
                // #ifdef APP-ANDROID
                const size = new FileInputStream(res.tempFilePath.substring("file://".length)).available() / 1024;
                this.afterCompressImageInfo = this.afterCompressImageInfo.concat(`图片大小: ${size}KB`);
                // #endif
              }
            });
          },
          fail: (err) => {
            uni.showModal({
              title: "压缩图片失败",
              content: JSON.stringify(err),
              showCancel: false
            });
          },
          complete: (_) => {
            uni.hideLoading();
          }
        });
      },
      chooseImage() {
        uni.chooseImage({
          count: 1,
          sizeType: ["original"],
          sourceType: ["album"],
          success: (res) => {
            this.beforeCompressPath = res.tempFilePaths[0];
            uni.getImageInfo({
              src: res.tempFilePaths[0],
              success: (_res) => {
                this.beforeCompressImageInfo = `图片宽度: ${_res.width}\n图片高度: ${_res.height}\n`;
                // #ifdef APP-ANDROID
                const size = new FileInputStream(res.tempFilePaths[0].substring("file://".length)).available() / 1024;
                this.beforeCompressImageInfo = this.beforeCompressImageInfo.concat(`图片大小: ${size}KB`);
                // #endif
              }
            });
          }
        });
      },
      onQualityConfirm(value : number) {
        this.quality = value;
      },
      onCompressedWidthConfirm(value : string) {
        this.compressedWidth = parseInt(value);
      },
      onCompressedHeightConfirm(value : string) {
        this.compressedHeight = parseInt(value);
      },
      onRotateConfirm(value : number) {
        this.rotate = value;
      },
      testCompressImage() {
        uni.compressImage({
          src: this.imageSrcForTest,
          quality: 50,
          compressedWidth: 100,
          compressedHeight: 100,
          success: (res) => {
            uni.getImageInfo({
              src: res.tempFilePath,
              success: (_res) => {
                let beforeCompressSize : number, afterComoressSize : number;
                // #ifdef APP-ANDROID
                beforeCompressSize = new FileInputStream(UTSAndroid.convert2AbsFullPath(this.imageSrcForTest)).available();
                afterComoressSize = new FileInputStream(res.tempFilePath.substring("file://".length)).available();
                // #endif
                this.imageInfoForTest = {
                  "width": _res.width,
                  "height": _res.height,
                  "isSizeReduce": afterComoressSize < beforeCompressSize
                };
              }
            });
          },
          fail: (_) => {
            this.imageInfoForTest = null;
          }
        });
      }
    }
  }
</script>

<style>
  .image {
    flex: 1;
  }

  .image-container {
    flex-direction: row;
  }
</style>

# 通用类型

# GeneralCallbackResult

名称 类型 必备 默认值 兼容性 描述
errMsg string - - 错误信息