HarmonyOS CanvasRenderingContext2D内容如何导出为一个图片文件

使用CanvasRenderingContext2D的drawImage方法画的二维码和logo图片,如何使用fs模块导出成一个图片文件到沙箱中。实验使用CanvasRenderingContext2D的getImageData方法配合fs的write方法生成的文件无法打开。

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Excelsior_abit

请参考如下代码做文件保存

async writePic(imgData: ImageData) {
  let times = new Date().getTime();
  let path = this.filesDir + '/' + times + '.jpg'
  try {
    let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    let uint8Array = new Uint8Array(imgData.data.buffer as ArrayBuffer);
    this.convertRGBAtoBGRA(uint8Array, imgData.width, imgData.height)
    let pixmap: PixelMap = await image.createPixelMap(uint8Array.buffer as ArrayBuffer, {
      size: { height: imgData.height, width: imgData.width }
    })

    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
    const imagePackerApi: image.ImagePacker = image.createImagePacker();
    imagePackerApi.packToFile(pixmap, file.fd, packOpts, (err: BusinessError) => {
      if (err) {
        console.error('packToFile failed.');
      } else {
        console.info('packToFile succeeded.');
      }
    })
  } catch (err) {
    let er = err as BusinessError
    console.error(`writePic failed, code is ${er.code}, message is ${er.message}`);
  }
  ;
}

convertRGBAtoBGRA(data: Uint8Array, width: number, height: number) {
  for (let i = 0; i < width * height * 4; i += 4) {
    let temp = data[i];
    data[i] = data[i + 2];
    data[i + 2] = temp;
  }
}
分享
微博
QQ
微信
回复
7天前
相关问题
HarmonyOS CanvasRenderingContext2D使用问题
63浏览 • 1回复 待解决