可参考如下demo,详情请参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-encoding-V5let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; let imagePackerApi = image.createImagePacker(); const context: Context = getContext(this); const resourceMgr = context.resourceManager; let imageBuffer = await resourceMgr.getMediaContent($r('app.media.ic_low')); const imageSource: image.ImageSource = image.createImageSource(imageBuffer.buffer); let decodingOptions: image.DecodingOptions = { editable: true, desiredPixelFormat: 3, rotate: 90 } // 创建pixelMap并进行简单的旋转和缩放 imageSource.createPixelMap(decodingOptions).then((pixelMap: PixelMap) => { this.pixelMap = pixelMap // pixelmap 转base64 先要有一个packing的过程 imagePackerApi.packing(pixelMap, packOpts).then((data: ArrayBuffer) => { let base64Str = buffer.from(data).toString('base64') let resultBase64Str = "data:image/png;base64," + base64Str this.resultBase64Str = resultBase64Str }).catch((error: BusinessError) => { console.error('Failed to pack the image. And the error is: ' + error); }) pixelMap.release(); }) //重点提示: pixelmap转base64 不能直接转,先要加一个packing的过程,下面的方法是一个错误的实例,转出来的base64字符串不对。 let pixelMap = await imageSource.createPixelMap(opts); console.log("pixelMap.getPixelBytesNumber():" + pixelMap.getPixelBytesNumber()) let arrayBuffer = new ArrayBuffer(pixelMap.getPixelBytesNumber()); pixelMap.readPixelsToBuffer(arrayBuffer) console.log("arrayBuffer" + arrayBuffer) let base64Str = buffer.from(arrayBuffer).toString(Constants.BASE_64); let resultBase64Str = "data:image/png;base64," + base64Str
可参考如下demo,详情请参考:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-encoding-V5