参考示例如下:generateBarcode.createBarcodetg生成二维码pixelMap对象,再将pixelMap转为base64字符串。let width = 300 let options: generateBarcode.CreateOptions = { scanType: scanCore.ScanType.QR_CODE, height: width, width: width } // 码图生成接口,成功返回PixelMap格式图片 generateBarcode.createBarcode(url, options, (error: BusinessError, pixelMap: image.PixelMap) => { if (error) { QDLogUtils.error(`createBarcode error ${JSON.stringify(error)}`); } else { QDStringUtils.pixelMapToBase64String(pixelMap).then((str) => { this.toSuccessCallback(`data:image/jpeg;base64,${str}`) }) } }) async pixelMapToBase64String(pixelMap: image.PixelMap): Promise<string> { const imagePackerApi: image.ImagePacker = image.createImagePacker(); let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 }; try { let readBuffer = await imagePackerApi.packing(pixelMap, packOpts) let bufferArr = new Uint8Array(readBuffer) let str = new util.Base64Helper().encodeToStringSync(bufferArr) return str } catch (err) { QDLogUtils.error(`pixelMapToBase64String err = ${err}`) } return '' }将resource中图片转base64:1、resource中图片转imagesource:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-decoding-V5\#ZH-CN\_TOPIC\_0000001847052324\_\_开发示例-对资源文件中的图片进行解码2、imagesource先编码,再转base64:const imagePackerApi = image.createImagePacker(); let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 }; imagePackerApi.packing(this.imagesource, packOpts).then(async (data: ArrayBuffer) => { // data 为打包获取到的文件流,写入文件保存即可得到一张图片 if (data) { const imageSource: image.ImageSource = image.createImageSource(data); let decodingOptions: image.DecodingOptions = { editable: true, desiredPixelFormat: 3, } // this.pixmap2= await imageSource.createPixelMap(decodingOptions) let buf: buffer.Buffer = buffer.from(data); let baseStr: string = buf.toString('base64', 0, buf.length); console.log(JSON.stringify(baseStr)) //送显 this.imgStr = "data:image/jpeg;base64," + baseStr; } }).catch((error: BusinessError) => { console.error('Failed to pack the image. And the error is: ' + error); })
参考示例如下:generateBarcode.createBarcodetg生成二维码pixelMap对象,再将pixelMap转为base64字符串。
将resource中图片转base64:
1、resource中图片转imagesource:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-decoding-V5\#ZH-CN\_TOPIC\_0000001847052324\_\_开发示例-对资源文件中的图片进行解码
2、imagesource先编码,再转base64: