HarmonyOS 拍照完成后,得到的uri地址如何转换为base64格式?

如题:HarmonyOS 拍照完成后,得到的uri地址如何转换为base64格式?

阅读 520
1 个回答

可参考如下demo,详情请参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-encoding-V5

let 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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏