小程序开放平台

文档中心
基础
界面
网络
数据缓存
媒体
图片
chooseImage
previewImage
getImageInfo
saveImageToPhotosAlbum
compressImage
地图
视频
富文本
位置
开放接口
设备
XHSML
性能
文件
数据分析
画布

xhs.compressImage

开发
>
JS API
>
媒体
>
图片
>
compressImage
>
更新时间:2025-04-10 16:09:39

以Promise风格调用: 支持

压缩图片接口,可选压缩质量。iOS 仅支持压缩 JPG 格式图片。

参数

Object object

属性
类型
默认值
必填
说明
srcstring图片路径,图片的路径,支持本地路径、代码包路径
qualitynumber80压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)。
compressedWidthnumber压缩后图片的宽度,单位为px,若不填写则默认以compressedHeight为准等比缩放。
compressedHeightnumber压缩后图片的高度,单位为px,若不填写则默认以compressedWidth为准等比缩放。
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

object.success 回调函数

属性
类型
说明
tempFilePathstring压缩后图片的临时文件路径 (本地路径)
originalSizenumber压缩前图片的大小,单位字节
compressedSizenumber压缩后图片的大小,单位字节
errMsgstringcompressImage:ok

实例代码

// 调用 compressImage 压缩图片
xhs.compressImage({
  src: '/path/to/local/image.jpg', // 图片路径,支持本地路径或代码包路径
  quality: 70, // 压缩质量,范围 0~100,数值越小,质量越低,压缩率越高
  compressedWidth: 800, // 压缩后图片的宽度,单位 px
  compressedHeight: 600, // 压缩后图片的高度,单位 px
  success: (res) => {
    console.log('图片压缩成功:', res);
    console.log('压缩后图片路径:', res.tempFilePath);
    console.log('压缩前图片大小:', res.originalSize, '字节');
    console.log('压缩后图片大小:', res.compressedSize, '字节');
  },
  fail: (err) => {
    console.error('图片压缩失败:', err.errMsg);
  },
  complete: () => {
    console.log('compressImage 调用结束');
  }
});