#鸿蒙通关秘籍#如何在HarmonyOS应用中保存带有水印的图片?

HarmonyOS
2024-12-03 10:34:28
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
墨s梦境LDAP

在HarmonyOS应用中,保存带有水印的图片可以通过以下步骤实现:

  1. 首先,利用imageSource.createPixelMap从选定的图片中创建一个图像像素数据对象(pixelMap)。

    CONTEXT.resourceManager.getMediaContent(this.imageSource.id, (error, value) => {
      if (error) {
        return;
      }
      let imageSource = image.createImageSource(value.buffer);
      imageSource.getImageInfo((err, data) => {
        if (err) {
          return;
        }
        let opts = {
          editable: true,
          desiredSize: {
            height: data.size.height,
            width: data.size.width
          }
        }
        imageSource.createPixelMap(opts, async (err, pixelMap) => {
          ...
        })
      })
    })
    
  2. 创建一个OffscreenCanvas对象,并获取其绘图上下文,通过drawImage绘制图像,并使用fillText在图像上叠加水印。

    const offScreenCanvas = new OffscreenCanvas(data.size.width, data.size.height);
    const offScreenContext = offScreenCanvas.getContext('2d');
    offScreenContext.drawImage(pixelMap, 0, 0, offScreenCanvas.width, offScreenCanvas.height);
    offScreenContext.textAlign = 'right';
    offScreenContext.textBaseline = 'bottom';
    offScreenContext.fillStyle = '#fffa0606';
    offScreenContext.font = 32 * this.imageScale + 'vp';
    offScreenContext.shadowBlur = 20;
    offScreenContext.shadowColor = '#F3F3F3';
    offScreenContext.fillText('追逐繁星的太阳', offScreenCanvas.width - 20 * this.imageScale, offScreenCanvas.height - 20 * this.imageScale);
    
  3. 使用getPixelMap从OffscreenCanvas获取新的图像像素数据,并利用photoAccessHelper.createAsset生成保存路径。

    this.pixelMap = offScreenContext.getPixelMap(0, 0, offScreenCanvas.width, offScreenCanvas.height);
    const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(CONTEXT);
    const uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png');
    
  4. 使用imagePacker.packing将图像数据打包为buffer后,通过fs.writeSync方法将图像保存到生成的路径。

    if (this.pixelMap !== undefined) {
      const imagePacker = image.createImagePacker();
      const imageBuffer = await imagePacker.packing(this.pixelMap, { format: 'image/png', quality: 100 });
      try {
        let file = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
        fs.writeSync(file.fd, imageBuffer);
        fs.closeSync(file.fd);
      } catch (err) {
        console.log(`fs failed ${err.code},errMessage:message`);
      }
    }
    

分享
微博
QQ
微信
回复
2024-12-03 12:52:26
相关问题