Media APIs

compressImage

Compress large images to meet size restrictions for mini programs.

Overview

my.compressImage compresses large images to fulfill the size restrictions from some mini programs. You can specify the compression quality level based on your needs.

Sample Code

my.compressImage({
  apFilePaths: ['path/to/image1.jpg', 'path/to/image2.jpg'],
  compressLevel: 2,
  success: (res) => {
    console.log('Compressed images:', res.apFilePaths);
  },
  fail: (err) => {
    console.log('Compression failed:', err);
  }
});

Parameters

PropertyTypeRequiredDescription
apFilePathsArrayYesAn array of the image paths to be compressed.
compressLevelintNoThe image quality after the compress. Valid values are:
0: Low quality
1: Medium quality
2: High quality
4: The quality depends on the network. When the network is Wi-Fi, the image is compressed to the high-quality image. Otherwise, the image is compressed to the medium-quality image.

The default value is 4.
successFunctionNoThe callback method that indicates a successful call.
failFunctionNoThe callback method that indicates a failed call.
completeFunctionNoThe callback method that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Success Callback Function

PropertyTypeRequiredDescription
apFilePathsArrayYesThe local file path of the compressed image.

Error Code

Error CodeError MessageDescription
2Compress failedFailed to compress all images.
Invalid parameterFailed to compress one of all images.

Usage Notes

  • Multiple images can be compressed in a single call
  • The compressLevel parameter controls the quality-size tradeoff
  • Level 4 (default) automatically adjusts based on network conditions
  • Returns the compressed image paths in the success callback