一、学习笔记
HarmonyOS NEXT API 12
二、代码实例
1、base64 格式图片 转 FilePath(文件路径)
/**
* base64Img 转 FilePath
* @param context
* @param base64Str
* @returns
*/
export async function base64ImgConvertFilePath(context: Context, base64Str: string): Promise<string | undefined> {
try {
const filePath = context.cacheDir + "/xxx_" + new Date().getTime() + '.png';
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
const reg = new RegExp("data:image/\\w+;base64,")
const base64 = base64Str.replace(reg, "");
const dataBuffer = buffer.from(base64, 'base64').buffer;
const size = fs.writeSync(file.fd, dataBuffer);
//关闭文件
fs.closeSync(file);
return filePath
} catch (error) {
return undefined
}
}
2、图片uri 转 base64 格式
export async function uriConvertBase64(uri: string): Promise<string> {
let pixelMap = await uriOrPathConvertPixelMap(uri)
if (pixelMap == undefined) {
throw new Error(" uriConvertBase64 转换失败")
return ''
}
const packOptions: image.PackingOption = {
format: 'image/jpeg',
quality: 99 // 图片质量
}
let arrayBuffer = await image.createImagePacker().packing(pixelMap, packOptions)
let base64Str = buffer.from(arrayBuffer).toString('base64')
let resultBase64Str = "data:image/png;base64," + base64Str
return resultBase64Str
}
3、图片 pixMap 转 base64 格式
export async function pixMapConvertBase64(pixelMap: image.PixelMap): Promise<string> {
const packOptions: image.PackingOption = {
format: 'image/jpeg',
quality: 99 // 图片质量
}
let arrayBuffer = await image.createImagePacker().packing(pixelMap, packOptions)
let base64Str = buffer.from(arrayBuffer).toString('base64')
let resultBase64Str = "data:image/png;base64," + base64Str
return resultBase64Str
}
4、FilePath(文件路径) 转 uri
export async function filePathConvertUri(filePath:string): Promise<string | undefined>{
try {
let uri = fileUri.getUriFromPath(filePath)
return uri
} catch (err) {
return undefined
}
}
5、uri/filePath 转 pixelMap
export async function uriOrPathConvertPixelMap(path:string): Promise<image.PixelMap|undefined>{
try {
let file = fs.openSync(path, fs.OpenMode.READ_ONLY)
const imageSource: image.ImageSource = image.createImageSource(file.fd)
fs.closeSync(file)
let decodingOptions: image.DecodingOptions = {
editable: true,
desiredPixelFormat: 3,
}
let pixelMap = await imageSource.createPixelMap(decodingOptions)
return pixelMap
} catch (e) {
return undefined
}
}