HarmonyOS 拍照后的图片加水印

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

demo代码如下:

import { pickerImage, saveToFile, Utils } from '../utils/utils';
import image from '@ohos.multimedia.image';
import photoAccessHelper from '@ohos.file.photoAccessHelper'

@Entry
@Component
export struct ShuiYin {
  @State isDrawable: boolean = false
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private canvasRenderContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private scroller: Scroller = new Scroller()
  imageScale: number = 1
  @State imageHeight: number = 0
  @State pixelMap: PixelMap | undefined = undefined
  hValue: number = 0
  wValue: number = 0
  @State saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  } // 设置安全控件按钮属性

  build() {
    NavDestination(){
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
        Text("使用canvas处理图像")
          .width("100%")
          .fontColor(Color.White)
          .height(45)
          .fontSize(24)
          .backgroundColor("#70a1ff")
          .textAlign(TextAlign.Center)

        Column() {
          Scroll(this.scroller) {
            Canvas(this.canvasRenderContext)
              .backgroundColor(Color.Yellow)
              .onReady(() => {
                this.isDrawable = true
              })
              .id("imageContainer")
              .width("100%")
              .height(px2vp(this.imageHeight))
          }
          .scrollable(ScrollDirection.Vertical)
          .margin({ bottom: 8 })
          .border({ style: BorderStyle.Solid, width: 2, color: Color.Red })
          .borderRadius(10)
          .width("100%")
          .aspectRatio(1)
          .scrollBar(BarState.Off)

          Scroll() {
            Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceEvenly }) {
              Button("选取图像").onClick(async () => {
                let buffer = await pickerImage()
                this.onComplete(buffer)
              })
              Button("添加水印").onClick(async () => {
                if (this.isDrawable) {
                  this.canvasRenderContext.beginPath()
                  this.canvasRenderContext.font = `宋体 ${100 / this.imageScale}px}`
                  this.canvasRenderContext.textBaseline = "top"
                  this.canvasRenderContext.fillStyle = "#FFFFFF"
                  this.canvasRenderContext.rotate(Math.PI / 180 * 0)
                  this.canvasRenderContext.fillText("水印水印水印水印\n水印", 0 / this.imageScale, 0 / this.imageScale)
                  this.canvasRenderContext.rotate(-Math.PI / 180 * 0)
                  this.canvasRenderContext.closePath()
                }
              })
              SaveButton(this.saveButtonOptions)
                .onClick(async (event, result: SaveButtonOnClickResult) => {
                  if (result == SaveButtonOnClickResult.SUCCESS) {
                    try {
                      let context = getContext();
                      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
                      let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 创建媒体文件
                      if (this.pixelMap) {
                        let imageInfo = await this.pixelMap.getImageInfo()
                        let offCanvas = new OffscreenCanvas(px2vp(imageInfo.size.width), px2vp(imageInfo.size.height))
                        let offContext = offCanvas.getContext("2d")
                        let contextPixelMap = this.canvasRenderContext.getPixelMap(0, 0, this.canvasRenderContext.width, this.canvasRenderContext.height)
                        offContext.drawImage(contextPixelMap, 0, 0, offCanvas.width, offCanvas.height)
                        saveToFile(offContext.getPixelMap(0, 0, offCanvas.width, offCanvas.height), uri);
                      }
                    } catch (err) {
                      console.error('createAsset failed, message = ', err);
                    }
                  } else {
                    console.error('SaveButtonOnClickResult createAsset failed');
                  }
                })
            }
          }.backgroundColor(Color.White)
          .width("100%")
          .layoutWeight(1)
          .borderRadius(10)
        }
        .padding(8)
        .width("100%")
        .layoutWeight(1)
        .backgroundColor("#f1f2f6")
      }.width("100%").height("100%")

    }
  }

  // 加载图片
  onComplete(imageInfo: ArrayBuffer) {
    let imageSource: image.ImageSource = image.createImageSource(imageInfo);
    imageSource.getImageInfo((err, value) => {
      if (err) {
        return;
      }
      this.hValue = Math.round(value.size.height * 1);
      this.wValue = Math.round(value.size.width * 1);
      let defaultSize: image.Size = {
        height: this.hValue,
        width: this.wValue
      };

      let opts: image.DecodingOptions = {
        editable: true,
        desiredSize: defaultSize
      };
      imageSource.createPixelMap(opts, (err, pixelMap) => {
        if (err) {
        } else {
          let rect = Utils.getComponentRect("imageContainer")
          this.imageScale = (rect.right - rect.left) / this.wValue
          this.imageHeight = this.hValue * this.imageScale
          this.canvasRenderContext.transform(this.imageScale, 0, 0, this.imageScale, 0, 0)
          this.pixelMap = pixelMap
          this.canvasRenderContext.drawImage(this.pixelMap, 0, 0)
        }
      })
    })
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS是否支持图片加水印
345浏览 • 1回复 待解决
HarmonyOS PDF添加水印展示白屏
41浏览 • 1回复 待解决
HarmonyOS windows级别添加水印
39浏览 • 1回复 待解决
如何使用canvas添加水印
1346浏览 • 1回复 待解决
HarmonyOS 如何给 app 添加水印
386浏览 • 1回复 待解决
HarmonyOS 如何在app内全页面添加水印
38浏览 • 1回复 待解决
HarmonyOS 有没有对UI添加水印方法
75浏览 • 1回复 待解决
如何获取拍照图片地址
1992浏览 • 1回复 待解决
图片处理(加动态水印
359浏览 • 1回复 待解决
HarmonyOS 水印相机、水印视频
25浏览 • 1回复 待解决
HarmonyOS拍照调用openSync方法报错
645浏览 • 1回复 待解决
HarmonyOS 如何设置拍照不存图库?
15浏览 • 1回复 待解决