图片压缩在应用开发中是一个非常常见的需求,特别是在处理用户上传图片时,需要上传指定大小以内的图片。目前图片压缩支持jpeg、webp、png格式。本例中以jpeg图片为例介绍如何通过packing和scale实现图片压缩到目标大小以内
使用说明
- 进入页面,输入图片压缩目标大小,点击“图片压缩”按钮查看压缩后的图片。效果图中输入图片压缩目标大小为10kb,实际压缩小于等于10kb
实现思路
-
获取图片。从资源管理器获取要压缩的图片,创建ImageSource实例,设置解码参数DecodingOptions,使用createPixelMap获取PixelMap图片对象。
// 获取压缩前图片大小,用于页面上图片显示 async aboutToAppear() { // this.compress() const context: Context = getContext(this); const resourceMgr: resourceManager.ResourceManager = context.resourceManager; // 获取待压缩的图片 resourceMgr.getRawFileContent(this.imageSrc).then((fileData: Uint8Array) => { // 获取图片的ArrayBuffer const buffer = fileData.buffer.slice(0); this.sourceImageByteLength = buffer.byteLength; this.beforeCompressionSize = (this.sourceImageByteLength / BYTE_CONVERSION).toFixed(1); }).catch((err: BusinessError) => { console.log(TAG, `Failed to get RawFileContent with error message: ${err.message}, error code: ${err.code}`); }); }
-
图片压缩。先判断设置图片质量参数quality为0时,packing能压缩到的图片最小字节大小是否满足指定的图片压缩大小。如果满足,则使用packing方式二分查找最接近指定图片压缩目标大小的quality来压缩图片。如果不满足,则使用scale对图片先进行缩放,采用while循环每次递减0.4倍缩放图片,再用packing(图片质量参数quality设置0)获取压缩图片大小,最终查找到最接近指定图片压缩目标大小的缩放倍数的图片压缩数据
-
/** * 从rawfile中获取需要压缩的图片image_compression_before.jpeg,压缩 */ imageCompression(): void { // 获取图片。从资源管理器获取要压缩的图片,创建ImageSource实例,设置解码参数DecodingOptions,使用createPixelMap获取PixelMap图片对象。 // 获取resourceManager资源管理器 const resourceMgr: resourceManager.ResourceManager = this.context.resourceManager; // 获取资源管理器后,再调用resourceMgr.getRawFileContent()获取资源文件的ArrayBuffer。 resourceMgr.getRawFileContent(this.imageSrc).then((fileData: Uint8Array) => { // 获取图片的ArrayBuffer const buffer = fileData.buffer.slice(0); // 创建ImageSource实例 const imageSource: image.ImageSource = image.createImageSource(buffer); // 设置解码参数DecodingOptions,解码获取PixelMap图片对象。 const decodingOptions: image.DecodingOptions = { sampleSize: 1, // 缩略图采样大小 rotate: 0, // 旋转角度 editable: true, // 是否可编辑。当取值为false时,图片不可二次编辑,如crop等操作将失败 desiredSize: { width: 1000, height: 2000 }, // 期望输出大小image.size desiredPixelFormat: 3, // 解码的像素格式。3表示RGBA_8888 } // 创建pixelMap imageSource.createPixelMap(decodingOptions).then((originalPixelMap: image.PixelMap) => { this.beforeImgSrc = originalPixelMap // 压缩图片 imageCompressionMethod.compressedImage(originalPixelMap, this.maxCompressedImageSize, 0) .then((showImage: CompressedImageInfo) => { // 获取压缩后的图片信息 this.compressedImageSrc = fileUri.getUriFromPath(showImage.imageUri); this.compressedByteLength = showImage.imageByteLength; this.afterCompressionSize = (this.compressedByteLength / BYTE_CONVERSION).toFixed(1); // 图片压缩后的大小如果未能达到指定压缩目标大小。提示修改代码中的图片缩小倍数(REDUCE_SCALE),以便进一步压缩图片大小。 if (this.compressedByteLength / BYTE_CONVERSION > this.maxCompressedImageSize) { AlertDialog.show({ message: '图片压缩后的大小未能达到指定压缩目标大小。请尝试修改代码中的图片缩小倍数(REDUCE_SCALE),以便进一步压缩图片大小', alignment: DialogAlignment.Center }); } }) }).catch((err: BusinessError) => { console.log(TAG, `Failed to create PixelMap with error message: ${err.message},