HarmonyOS 多张string图片合并成一张

图片合并逻辑有问题吗?为什么会闪退呢?

HarmonyOS 多张string图片合并成一张 -鸿蒙开发者社区

HarmonyOS
18h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

可以参考这个demo:

import { image } from '@kit.ImageKit';
import { ArrayList, util } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private signSettings: RenderingContextSettings = new RenderingContextSettings(true)
  private signContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.signSettings)
  @State transcriptionMark: number = 0
  private copySettings: RenderingContextSettings = new RenderingContextSettings(true)
  private copyContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.copySettings)
  @State copyImage: string[] = []
  private timerId: number = -1
  private lastX: number = 0;
  private lastY: number = 0;
  private isDown: Boolean = false;
  @State copyContent: string = '本人已阅读保险条款'
  @State imagePixelMap: image.PixelMap | undefined = undefined
  @State orgImage: image.PixelMap | undefined = undefined
  @State list: ArrayList<image.ImageSource> = new ArrayList<image.ImageSource>()

  aboutToAppear(): void {
    this.list.clear()
  }

  draw(context: CanvasRenderingContext2D, startX: number, startY: number, endX: number, endY: number) {
    // 起点
    context.moveTo(startX, startY);
    // 终点
    context.lineTo(endX, endY);
    // 调用 stroke,即可看到绘制的线条
    context.stroke();
  }

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Column({ space: '10vp' }) {
        Row({ space: '9vp' }) {
          Column() {
            Grid() {
              ForEach(this.copyImage, (image: string) => {
                GridItem() {
                  Image(image)
                    .width('100%')
                    .height('100%')
                }
              }, (day: string) => day)
            }
            .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr')
            .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
            .columnsGap(8)
            .rowsGap(8)
            .width('98%')
            .height('98%')
          }
          .layoutWeight(3)
          .backgroundColor('#EEEEEE')
          .borderRadius('10vp')
          .height('100%')

          Stack() {
            Canvas(this.signContext)
              .width('100%')
              .height('100%')
              .onReady(() => {
                this.signContext.beginPath()
                this.signContext.moveTo(0, 0)
                this.signContext.lineTo(this.signContext.width, this.signContext.height)
                this.signContext.moveTo(this.signContext.width, 0)
                this.signContext.lineTo(0, this.signContext.height)
                this.signContext.moveTo(this.signContext.width / 2, 0)
                this.signContext.lineTo(this.signContext.width / 2, this.signContext.height)
                this.signContext.moveTo(0, this.signContext.height / 2)
                this.signContext.lineTo(this.signContext.width, this.signContext.height / 2)
                this.signContext.setLineDash([10, 10])
                this.signContext.stroke()
              })
            Text(this.copyContent.substring(this.transcriptionMark, this.transcriptionMark + 1))
              .width('100%')
              .height('100%')
              .fontSize('130fp')
              .fontColor('#F0F0F0')
              .fontWeight(FontWeight.Bold)
              .textAlign(TextAlign.Center)

            Canvas(this.copyContext)
              .width('100%')
              .height('100%')
              .onReady(() => {
                this.copyContext.strokeStyle = "#ff000000"
                this.copyContext.lineWidth = 5
              })
              .gesture(PanGesture().onActionStart(event => {
                clearTimeout(this.timerId);
                this.isDown = true;
                // 按下时的点作为起点
                this.lastX = event.fingerList[0].localX;
                this.lastY = event.fingerList[0].localY
                // 创建一个新的路径
                this.copyContext.beginPath();
                // console.log("onActionStart() ")
              })
                .onActionUpdate(event => {
                  // console.log("onActionUpdate() ")
                  clearTimeout(this.timerId);
                  // 没有按下就不管
                  if (!this.isDown) {
                    return;
                  }
                  const offsetX = event.fingerList[0].localX
                  const offsetY = event.fingerList[0].localY
                  // 调用绘制方法
                  this.draw(this.copyContext, this.lastX, this.lastY, offsetX, offsetY);
                  // 把当前移动时的坐标作为下一次的绘制路径的起点
                  this.lastX = offsetX;
                  this.lastY = offsetY;
                })
                .onActionEnd(event => {
                  // console.log("onActionEnd() ")
                  this.isDown = false;
                  // 关闭路径
                  this.copyContext.closePath();
                  this.timerId = setInterval(() => {
                    clearTimeout(this.timerId);
                    let image = this.signContext.getImageData(0, 0, this.copyContext.width, this.copyContext.height)
                    let url = this.copyContext.toDataURL("image/png", 0.5)
                    this.copyImage[this.transcriptionMark] = url
                    this.copyContext.clearRect(0, 0, this.copyContext.width, this.copyContext.height)
                    this.transcriptionMark++
                  }, 2000)
                }), GestureMask.Normal)

          }
          .layoutWeight(2)
          .borderRadius('10vp')
          .borderColor('#CECECE')
          .height('100%')
          .borderWidth('3vp')
          .id('ban')
        }
        .height('58%')

        Row() {
          Row({ space: '10vp' }) {
            Button('完成')
              .width('80vp')
              .height('35vp')
              .fontSize('14fp')
              .backgroundColor('#fffe0403')
              .onClick(async () => {
                this.imagePixelMap = await this.combinePic(this.copyImage)
              })
          }
          .alignSelf(ItemAlign.End)
          .margin({ right: '20vp', bottom: '20vp' })
        }
        .width('100%')
        .justifyContent(FlexAlign.End)

      }
      .height('50%')

      Image(this.imagePixelMap)
        .width(200)
        .height(200)
        .backgroundColor(Color.Yellow)
        .objectFit(ImageFit.Contain)

      Image(this.orgImage)
        .enableAnalyzer(true)
        .width(200)
        .height(200)
        .border({ width: 1 })
    }
    .height('100%')
    .width('100%')
  }

  async combinePic(pics: string[]) {
    if (pics.length < 2) {
      let helper = new util.Base64Helper();
      let buffer: ArrayBuffer = helper.decodeSync(pics[0].substring(22), util.Type.MIME).buffer as ArrayBuffer;
      let imageSource = image.createImageSource(buffer);
      const imageInfo = await imageSource.getImageInfo();
      let opts: image.DecodingOptions = {
        editable: true,
        desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
        desiredSize: { width: imageInfo.size.width, height: imageInfo.size.height }
      };
      let pixelMap = await imageSource.createPixelMap(opts);
      return pixelMap;
    }
    const tempPath = pics[0];
    const imageSource = image.createImageSource(tempPath);
    const imageInfo = await imageSource.getImageInfo();
    const singleWidth = imageInfo.size.width;
    const singleHeight = imageInfo.size.height;
    const combineOpts: image.InitializationOptions = {
      alphaType: 0,
      editable: true,
      pixelFormat: image.PixelMapFormat.BGRA_8888,
      size: { width: singleWidth * pics.length, height: singleHeight }
    }
    const singleOpts: image.DecodingOptions = {
      editable: true,
      desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
      desiredSize: { width: singleWidth, height: singleHeight }
    };
    const combineColor = new ArrayBuffer(combineOpts.size.width * combineOpts.size.height * 4);
    let singleColor = new ArrayBuffer(singleOpts.desiredSize!.width * singleOpts.desiredSize!.height * 4);
    const newPixelMap = await image.createPixelMap(combineColor, combineOpts);
    for (let i = 0; i < pics.length; i++) {
      let singlePath = pics[i];
      let imageSource = image.createImageSource(singlePath);
      const singlePixelMap = await imageSource.createPixelMap(singleOpts);
      await singlePixelMap.readPixelsToBuffer(singleColor);

      let area: image.PositionArea = {
        pixels: singleColor,
        offset: 0,
        stride: singleWidth * 4,
        region: {
          size: { height: singleHeight, width: singleWidth },
          x: singleWidth * i,
          y: 0
        }
      }
      await newPixelMap.writePixels(area);
    }
    let combinePixelMap = newPixelMap;
    return combinePixelMap
  }
}
分享
微博
QQ
微信
回复
16h前
相关问题
HarmonyOS 多张图片拼接为一张
0浏览 • 1回复 待解决
HarmonyOS 多张画布横向合成一张图片
31浏览 • 1回复 待解决
如何吸取一张图片的色值?
429浏览 • 1回复 待解决
HarmonyOS 获取手机最新的一张图片
36浏览 • 1回复 待解决
如何将一张图片转化为PixelMapElement
10040浏览 • 1回复 待解决
如何保存一张PNG图片到相册中
1876浏览 • 1回复 待解决