HarmonyOS 鸿蒙Next图片二进制数据流转化为base6格式
HarmonyOS 鸿蒙Next图片二进制数据流转化为base6格式
在js中是下面这样转换的(item2.data就是收到的后台响应的二进制数据流)。鸿蒙中应该如何转换?
可以使用系统api
import util from '@ohos.util';
// base64
let base64Helper = new util.Base64Helper()
let uint8Arr = new Uint8Array(readBuffer)
WinsleiLogManager.hilogIWithTag(TAG, 'selectPhoto Uint8Array, uint8Arr: ’ + JSON.stringify(uint8Arr));
let pixelStr = base64Helper.encodeToStringSync(uint8Arr)
// let pixelStr = this.arrayBufferToBase64(uint8Arr)
this.base64Str = ‘data:image/jpg;base64,’ + pixelStr
WinsleiLogManager.hilogIWithTag(TAG, 'selectPhoto base64, base64Str: ’ + this.base64Str);
也有其他的方法,可以参考下面的博客
OpenHarmony图片转Base64编码开发流程_openharmony base64-CSDN博客
可以使用util.Base64Helper()来实现,参考代码如下:
import { util } from '@kit.ArkTS';
// 将base64转为二进制流
let base64Helper = new util.Base64Helper();
let buff = ''; //此处为base64字符串
let result = base64Helper.decodeSync(buff);
let uint8Arr = new Uint8Array(result);
// 将二进制流转为base64
let pixelStr = base64Helper.encodeToStringSync(uint8Arr)
let base64Str = 'data:image/jpg;base64,' + pixelStr
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
/**
* packing压缩
* [@param](/user/param) pixelMap:原始待压缩图片的PixelMap
* [@param](/user/param) quality:图片质量参数 0 ~ 100
* [@param](/user/param) format:目标格式。当前只支持jpg、webp 和 png。image/[png|jpeg|webp]
* [@returns](/user/returns) data:返回压缩后的图片数据
*/
public static async packing(pixelMap: image.PixelMap, quality: number, format: string = "image/jpeg"): Promise<ArrayBuffer> {
const imagePackerApi = image.createImagePacker();
const packOpts: image.PackingOption = { format: format, quality: quality };
const data: ArrayBuffer = await imagePackerApi.packing(pixelMap, packOpts);
return data;
}
public static async pixelMapToBase64(pixelMap: image.PixelMap, quality: number): Promise<string> {
const buffer = await ImgUtil.packing(pixelMap, quality);
const bytes = new Uint8Array(buffer);
let base64 = await new util.Base64Helper().encodeToString(bytes, util.Type.BASIC)
return base64;
}
实时下面方法:
- ImagePacker 获取的 arrayBuffer 可以转为 base64,参考代码:
```
let imageData: ArrayBuffer
let base64 = new util.Base64Helper(); // 实例化 Base64Helper
let data = base64.encodeSync(new Uint8Array(imageData.slice(0, imageData.byteLength))) // 转换成 Uint8Array
console.info(`data 长度:${data.length}`)
console.info(`data:${data}`)
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true })
let retStr = textDecoder.decodeWithStream( data, {stream: false}); // 可以把 Uint8Array 转码成 base64
```
- 通过 photoPicker 选择图片获取相册图片路径后进行转换,参考代码:
```jav
import fs from '@ohos.file.fs';
import buffer from '@ohos.buffer';
export function imageToBase64(filePath: string, bufferLen = 409600) {
try {
const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
const arrayBuffer = new ArrayBuffer(bufferLen);
const readLen = fs.readSync(file.fd, arrayBuffer);
const buf = buffer.from(arrayBuffer, 0, readLen);
const base64 = buf.toString('base64');
fs.closeSync(file);
return base64;
} catch (e) {
console.error('file err:', JSON.stringify(e));
return ''
}
}
export function base64ToImage(base64: string, filePath: string) {
try {
const reg = new RegExp();
const str = base64.replace(reg, "");
const dataBuffer = buffer.from(str, 'base64');
const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, dataBuffer.buffer);
fs.closeSync(file);
} catch (e) {
console.error('
}
}
```
- 通过调用 cameraPicker 获取图片进行转换,参考代码:
```
Button('调起相机,图片存图库里')
.onClick(async () => {
try {
const pickerProfile: picker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
};
const pickerResult: picker.PickerResult = await picker.pick(this.context, [picker.PickerMediaType.PHOTO, picker.PickerMediaType.VIDEO], pickerProfile);
const uri = pickerResult.resultUri;
// 可以根据 uri 打开该文件
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY)
let stat = fs.statSync(file.fd)
let arrayBuffer = new ArrayBuffer(stat.size)
fs.readSync(file.fd, arrayBuffer)
fs.fsyncSync(file.fd)
fs.closeSync(file)
// arrayBuffer 转 base64
const uint8Array = new Uint8Array(arrayBuffer);
const base64Helper = new util.Base64Helper();
const base64Image = base64Helper.encodeToStringSync(uint8Array);
console.info('base64Image: ' base64Image);
// Image 支持 Base
}
}
```
在HarmonyOS(鸿蒙)系统中,将图片二进制数据流转化为Base64格式,你通常需要在你的应用代码中执行此操作。这通常涉及读取图片的字节数据,然后使用Base64编码算法对这些字节进行编码。
在Java或Kotlin(鸿蒙应用开发常用的语言)中,你可以使用java.util.Base64
类来实现。首先,将图片文件读取为字节数组,然后使用Base64.getEncoder().encodeToString(byte[] src)
方法将字节数组编码为Base64字符串。
如果问题依旧没法解决请加我微信,我的微信是itying888。