如何实现PixelMap和base64的相互转换

需要上传服务器等场景中,需要实现PixelMap和base64的互相转换。

HarmonyOS
2024-05-23 22:05:30
浏览
收藏 1
回答 1
待解决
回答 1
按赞同
/
按时间
fujiang1981
1

PixelMap转base64:PixelMap转换成base64必须先使用imagePacker将pixelMap压缩后再进行base64,若要实现无损压缩,将PixelMap压缩成PNG,即调用imagePacker时,let packOpts: image.PackingOption = { format: 'image/png', quality: 100 };

base64转PixelMap:先将base64字符串解析成arraybuffer,然后利用这个arraybuffer构建新PixelMap,需要注意的是,使用decodeSync对base64字符串解码时,传入的base64字符串不能有'data:image/jpeg;base64,'这样的前缀。

参考代码:

PixelMap转base64参考如下代码:

let resourceManager = getContext(this).resourceManager 
let imageArray = await resourceManager.getMediaContent($r('app.media.beer')); 
let pixelBuffer = new Uint8Array(imageArray).buffer as Object as ArrayBuffer 
let imageResource = image.createImageSource(pixelBuffer); 
let opts: image.DecodingOptions = { editable: true } 
let pixelMap = await imageResource.createPixelMap(opts); 
  
// 转换成base64 
const imagePackerApi: image.ImagePacker = image.createImagePacker(); 
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 }; 
imagePackerApi.packing(pixelMap, packOpts).then((data: ArrayBuffer) => { 
  let buf: buffer.Buffer = buffer.from(data); 
  this.base64 = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length); 
  console.info('base64: ' + this.base64); 
})

base64转PixelMap参考如下代码:

import util from '@ohos.util'; 
  
let helper = new util.Base64Helper(); 
// 传入的base64字符串内容为:/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHRyWFlaAAABZ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da54j1/OHAcQ9A6rDft5m+fl26urVrw14xg6CcMHLUC6VOpm+gaYTJ0+I8cPrZz3LpN1eYDYH5UuX+kk889eA6vuw1RHj+5r8cH+Ce0I/hACb+K3/H7cPUPOI4jya69Gk8F9vbm6AHmEIr3kpXO3Fg97P0Pfmh9Me+H2a4yhLnSCaKnyDk/NzBk5mYftO+F1CxHk4lpT7IAjwiREeAEJ3vJUxPD4sczPCnq7c8SPypeQFOEj8bx/rvsGIRTmjmZny+8SODljimcD+YpgihX2P+eusIAsCs6ROzjeZ+cZsT9PT0BhyDCI6D78VMz/AIuZ4YT2f0x9n3xYQBHhCEAIQhACEIQAhCEAIQhACEIQAhCEAIQhACEIQAhCEAIQhACEIQAhCEA 
let buffer: ArrayBuffer = helper.decodeSync(this.base64, util.Type.MIME).buffer as ArrayBuffer; 
let imageSource = image.createImageSource(buffer); 
let opts: image.DecodingOptions = { editable: true }; 
this.pixelMap = await imageSource.createPixelMap(opts);
分享
微博
QQ
微信
回复
2024-05-24 21:55:34
相关问题
如何base64转换成图片?
8528浏览 • 2回复 待解决
PixelMap怎么转Base64?(非Java)
1256浏览 • 2回复 待解决
怎么把PixelMap图片转BASE64
7924浏览 • 1回复 待解决
pxvp之间如何相互转换
685浏览 • 1回复 待解决
验证pixelmap数据buffer转base64是否正常
598浏览 • 1回复 待解决
Uint8Arraystring之间相互转换
395浏览 • 1回复 待解决
如何进行base64编码,有人知道吗?
225浏览 • 1回复 待解决
js canvas转base64编码图片不全
9125浏览 • 1回复 待解决
有没有base64转化相关代码?
284浏览 • 0回复 待解决
base64字符串如何转为图片并保存
1068浏览 • 1回复 待解决
如何在ArkTS中实现JSONMap转换
572浏览 • 1回复 待解决
如何将app.media.app_icon,转换PixelMap
719浏览 • 1回复 待解决
flutter鸿蒙如何相互调用?
12528浏览 • 3回复 待解决
如何实现ArkTS与C/C++HashMap转换
434浏览 • 0回复 待解决