实现图片添加水印功能鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-3-6 17:12
浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例基于图片处理能力、Canvas组件以及组合手势拖动组件实现了为图片添加文字水印和水印图像的功能,添加的水印可拖动。

实现图片添加水印功能源码链接

效果预览

实现图片添加水印功能鸿蒙示例代码-鸿蒙开发者社区

使用说明

  1. 点击“选取图像”按钮,从图库选择想要添加水印的图片。
  2. 点击“选取水印图像”按钮,从图库选择图片作为水印图像,长按水印可拖动选择位置。
  3. 点击“添加文字水印”按钮,在图片左上角添加文字水印,长按水印可拖动选择位置。
  4. 点击“保存图片”,应用向用户申请授权,用户同意后会将图片保存到图库。

实现思路

选取水印图像

调用图片处理模块的image.createImageSource方法,通过缓冲区创建图片源实例,利用getImageInfo接口获取图片信息,创建PixelMap对象,最后释放图片源实例获取水印图像。核心代码如下,源码参考Index.ets

onWaterComplete(imageInfo: ArrayBuffer) {

    let imageSource: image.ImageSource = image.createImageSource(imageInfo);
    imageSource.getImageInfo((err, value) => {
      if (err) {
        return;
      }
      let defaultSize: image.Size = {
        height: Math.round(value.size.height * 1),
        width: Math.round(value.size.width * 1)
      };

      let opts: image.DecodingOptions = {
        editable: true,
        desiredSize: defaultSize
      };
      imageSource.createPixelMap(opts, (err, pixelMap) => {
        if (err) {
        } else {
          this.watermarkImgList.push(new watermarkImgType(pixelMap, Math.random().toString(),
            defaultSize.width / defaultSize.height))
        }
      })
    })
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

拖动水印

通过配置GestureGroup实现了长按和拖动的组合手势顺序识别,先触发长按手势事件,触发成功后可触发拖动手势事件,从而实现长按水印可拖动的功能。核心代码如下,源码参考component.ets。

.gesture(
        // 以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件
        GestureGroup(GestureMode.Sequence,
          LongPressGesture({ repeat: false })
            .onAction((event?: GestureEvent) => {
              this.isStart = true
            })
          ,

          PanGesture()
            .onActionStart(() => {
              console.info('pan start')
            })
            .onActionUpdate((event?: GestureEvent) => {
              if (event) {
                this.item.offsetX = this.item.positionX + event.offsetX
                this.item.offsetY = this.item.positionY + event.offsetY
              }
              console.info('pan update')
            })
            .onActionEnd(() => {
              this.isStart = false
              this.item.positionX = this.item.offsetX
              this.item.positionY = this.item.offsetY
              console.info('pan end')
            })
        )
          .onCancel(() => {
            this.isStart = false
          })
      )
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

分类
收藏
回复
举报
回复
    相关推荐