鴻蒙常見的圖片文件操作

一、學(xué)習(xí)筆記

HarmonyOS NEXT API 12


二、代碼實例

1、base64 格式圖片 轉(zhuǎn) FilePath(文件路徑)

/**
 * base64Img 轉(zhuǎn) 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);
    //關(guān)閉文件
    fs.closeSync(file);
    return filePath
  } catch (error) {
    return undefined
  }
}

2、圖片uri 轉(zhuǎn) base64 格式

export async function uriConvertBase64(uri: string): Promise<string> {

  let pixelMap = await uriOrPathConvertPixelMap(uri)
  if (pixelMap == undefined) {
    throw new Error(" uriConvertBase64 轉(zhuǎn)換失敗")
    return ''
  }
  const packOptions: image.PackingOption = {
    format: 'image/jpeg',
    quality: 99 // 圖片質(zhì)量
  }
  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 轉(zhuǎn) base64 格式

export async function pixMapConvertBase64(pixelMap: image.PixelMap): Promise<string> {
 const packOptions: image.PackingOption = {
    format: 'image/jpeg',
    quality: 99 // 圖片質(zhì)量
  }
  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(文件路徑) 轉(zhuǎn) 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 轉(zhuǎn) 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
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容