HarmonyOS 扫描车牌页面的UI应该怎么画出来,背景是相机,然后屏幕中需要放置有自定义的图片和按钮

扫描车牌页面的UI应该怎么画出来,背景是相机,然后屏幕中需要放置有自定义的图片和按钮,并且上传图片到服务器应该怎么上传,给个demo

HarmonyOS
2025-01-10 08:53:06
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

可以通过XComponent结合stack的方式实现相机背景上有图片和按钮的样式,上下扫描可以通过动画实现,若是需要通过拍照识别文字可以通过textRecognition进行识别具体实现可以参考文档:

基于相机管理和文字识别接口,实现识别提取照片内文字的功能demo:

https://communityfile-drcn.op.dbankcloud.cn/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20240605105422.00621219926688988597809999791097:50001231000000:2800:34BCD53E6EF6942583E8E3124E8C9CE2E9E58AD58762D55E2C0AFCCAEC27652D.zip?needInitFileName=true

通用文字识别:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/core-vision-text-recognition-V5

相机参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/camera-preparation-V5

相机示例代码:

https://gitee.com/harmonyos_samples/camera#%E4%BB%8B%E7%BB%8D

动画参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-keyframeanimateto-V5

应用文件上传下载文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5

// xxx.ets
import { display } from '@kit.ArkUI';
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { abilityAccessCtrl, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { TAG } from '@ohos/hypium/src/main/Constant';

import { textRecognition } from '@kit.CoreVisionKit';

@Entry
@Component
struct Index {
  private surfaceId: string = ''
  private xComponentContext: Record<string, () => void> = {}
  private xcomponentController: XComponentController = new XComponentController();
  private screenHeight: number = this.getDeviceHeight();
  private xcomponentHeight: number = this.screenHeight - 264;
  private photoOutput: camera.PhotoOutput | undefined = undefined;
  private context = getContext(this);


  private cameraManager: camera.CameraManager | undefined = undefined;
  private cameraInput: camera.CameraInput | undefined = undefined;
  @State imageSize: image.Size = { width: 1920, height: 1080 };
  private previewOutput: camera.PreviewOutput | undefined = undefined;
  private previewOutput2: camera.PreviewOutput | undefined = undefined;
  private imageReceiver: image.ImageReceiver | undefined = undefined;
  private cameraSession: camera.PhotoSession | undefined = undefined;
  @State buffer: ArrayBuffer | undefined = undefined;

  @State pixelMap: PixelMap | undefined = undefined;
  @State dataValues:string = '';

  aboutToAppear(): void {
    let permissions: Array<Permissions> = [
      'ohos.permission.CAMERA',
      'ohos.permission.WRITE_MEDIA',
      'ohos.permission.READ_MEDIA',
      'ohos.permission.MEDIA_LOCATION',
    ];
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(this.context, permissions).then((data: PermissionRequestResult) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] != 0) {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
          return;
        }
      }
      console.info(`${TAG} Success to request permissions from user. authResults is ${grantStatus}.`);
    }).catch((err: BusinessError) => {
      console.error(`${TAG} Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
    })
  }

  getDeviceHeight(): number {
    let displayObject = display.getDefaultDisplaySync();
    let screenPixelHeight = displayObject.height;
    let screenDensityDPI = displayObject.densityDPI;
    return screenPixelHeight * (160 / screenDensityDPI);
  }

  async XComponentinit() {
    this.xcomponentController.setXComponentSurfaceSize({
      surfaceWidth: 190,
      surfaceHeight: 100
    });
    this.surfaceId = this.xcomponentController.getXComponentSurfaceId();
    // await this.camera.initCamera(this.surfaceId);
  }

  build() {
    Row() {
      Stack() {
        Column() {
          Row() {
            XComponent({
              id: 'xcomponent1',
              type: 'surface',
              controller: this.xcomponentController
            })
              .onLoad(async () => {
                this.XComponentinit()
                setTimeout(async () => {
                  await this.prepareCamera();
                }, 500);
              })
              .width('100%')
              .height(this.xcomponentHeight)
          }
          .width('100%')
          .margin({ top: '30vp' })
          .flexGrow(1)

          Column() {
            Image($r('app.media.app_icon'))
              .width('50vp')
              .height('50vp')
            Text(this.dataValues)
              .fontSize('12fp')
            Text('扫车牌')
              .fontSize('14fp')
              .fontColor(Color.White)
              .margin({
                top: '16vp',
                bottom: '16vp'
              })
            Row() {
              Row()
                .backgroundColor(Color.White)
                .width('60vp')
                .height('60vp')
                .border({
                  radius: '37vp'
                })
            }
            .onClick(async () => {

              let photoCaptureSetting: camera.PhotoCaptureSetting = {
                quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
                rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0
              }
              // 1、通过拍照流实现:点击拍照
              await this.photoOutput?.capture(photoCaptureSetting).catch((error: BusinessError) => {
                console.error(`CameraDemo Failed to capture the photo ${error.message}`); //不符合条件则进入
              })
            })
            .backgroundColor(Color.Black)
            .width('76vp')
            .height('76vp')
            .border({
              color: Color.White,
              width: '1vp',
              radius: '37vp'
            })
            .justifyContent(FlexAlign.Center)
            .alignItems(VerticalAlign.Center)
          }
          .width('100%')
          .flexShrink(0)
          .height('228vp')
          .backgroundColor(Color.Black)
          .alignItems(HorizontalAlign.Center)
        }
        .width('100%')
        .height('100%')
        .backgroundColor(Color.Black)

        Column({ space: 5 }) {
          Image(this.pixelMap)
            .width('200vp')
            .height('200vp')
        }

      }
    }
    .height('100%')
  }

  private async textRecognitionTest(imagePixelMap:image.PixelMap) {
    // 调用文本识别接口
    let visionInfo: textRecognition.VisionInfo = {
      pixelMap: imagePixelMap
    };
    let textConfiguration: textRecognition.TextRecognitionConfiguration = {
      isDirectionDetectionSupported: false
    };
    textRecognition.recognizeText(visionInfo, textConfiguration, (error: BusinessError, data: textRecognition.TextRecognitionResult) => {
      if (error.code !== 0) {
        return;
      }
      // 识别成功,获取对应的结果
      let recognitionString = JSON.stringify(data);
      // 将结果更新到Text中显示
      this.dataValues = data.value;
    });
  }

  createCameraManager() {
    // 创建CameraManager对象
    let cameraManager: camera.CameraManager = camera.getCameraManager(this.context);
    if (!cameraManager) {
      console.error('CameraDemo camera.getCameraManager error');
      return;
    }
    this.cameraManager = cameraManager;

    // 监听相机状态变化
    this.cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
      console.info(`CameraDemo camera: ${cameraStatusInfo.camera.cameraId}, status: ${cameraStatusInfo.status}`);
    });
  }

  async prepareCamera() {
    this.createCameraManager();

    if (!this.cameraManager) {
      console.error('CameraDemo cameraManager is undefined.')
      return;
    }

    // 获取支持指定的相机设备对象
    let cameraDevices: Array<camera.CameraDevice> = [];
    try {
      cameraDevices = this.cameraManager.getSupportedCameras();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo The getSupportedCameras call failed. error: ${JSON.stringify(err)}`)
    }

    cameraDevices.forEach((cameraDevice: camera.CameraDevice) => {
      console.info(`CameraDemo cameraId: ${cameraDevice.cameraId}, cameraPosition: ${cameraDevice.cameraPosition.toString()}, cameraType: ${cameraDevice.cameraType.toString()}, connectionType: ${cameraDevice.connectionType.toString()}`)
    })

    // 创建相机输入流
    try {
      this.cameraInput = this.cameraManager.createCameraInput(cameraDevices[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听cameraInput错误信息
    this.cameraInput.on('error', cameraDevices[0], (error: BusinessError) => {
      console.error(`CameraDemo Camera input error: ${JSON.stringify(error)}`);
    });

    // 打开相机
    try {
      await this.cameraInput.open();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo cameraInput open error. error: ${JSON.stringify(err)}`);
    }

    // 获取指定的相机设备对象支持的模式
    let cameraSceneModes: Array<camera.SceneMode> = [];
    try {
      cameraSceneModes = this.cameraManager.getSupportedSceneModes(cameraDevices[0]);
      cameraSceneModes.forEach((cameraSceneMode: camera.SceneMode) => {
        console.info(`CameraDemo cameraSceneMode: ${cameraSceneMode.toString()}`)
      })
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo The getSupportedSceneModes call failed. error: ${JSON.stringify(err)}`)
    }

    // 获取相机设备支持的输出流能力
    let cameraOutputCapability: camera.CameraOutputCapability = this.cameraManager.getSupportedOutputCapability(cameraDevices[0], camera.SceneMode.NORMAL_PHOTO)
    if (!cameraOutputCapability) {
      console.error('CameraDemo cameraManager.getSupportedOutputCapability error');
      return;
    }
    this.printCameraOutputCapability(cameraOutputCapability);
    let previewProfile = cameraOutputCapability.previewProfiles[0];
    cameraOutputCapability.previewProfiles.forEach((profile) => {
      if (profile.size.width == this.imageSize.width && profile.size.height == this.imageSize.height) {
        previewProfile = profile;
        return;
      }
    })
    this.imageSize = previewProfile.size;

    // 创建相机预览输出流
    try {
      this.previewOutput = this.cameraManager.createPreviewOutput(previewProfile, this.surfaceId);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听previewOutput错误信息
    this.previewOutput.on('error', (error: BusinessError) => {
      console.error(`CameraDemo previewOutput error: ${JSON.stringify(error)}`);
    });

    // 创建拍照输出流
    try {
      let photoProfile = cameraOutputCapability.photoProfiles[0];
      cameraOutputCapability.photoProfiles.forEach((profile) => {
        if (profile.size.width == this.imageSize.width && profile.size.height == this.imageSize.height) {
          photoProfile = profile;
          return;
        }
      })
      this.photoOutput = this.cameraManager.createPhotoOutput(photoProfile);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createPhotoOutput error ${JSON.stringify(err)}`);
    }
    if (this.photoOutput === undefined) {
      console.error('CameraDemo photoOutput is undefined.');
      return;
    }

    //调用上面的回调函数来保存图片
    this.setPhotoOutputCb(this.photoOutput);

    // 创建相机会话
    try {
      // this.cameraSession = this.cameraManager.createCaptureSession();
      this.cameraSession = this.cameraManager.createSession<camera.PhotoSession>(camera.SceneMode.NORMAL_PHOTO);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听session错误信息
    this.cameraSession.on('error', (error: BusinessError) => {
      console.error(`CameraDemo Capture session error: ${JSON.stringify(error)}`);
    });

    // 开始会话配置
    try {
      this.cameraSession.beginConfig()
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo beginConfig error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加相机输入流
    try {
      this.cameraSession.addInput(this.cameraInput)
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo addInput error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加拍照输出流
    try {
      this.cameraSession.addOutput(this.photoOutput);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo add photoOutput error. error: ${JSON.stringify(err)}`);
    }

    // 提交会话配置
    try {
      await this.cameraSession.commitConfig();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo captureSession commitConfig error: ${JSON.stringify(err)}`);
    }

    // 启动会话
    try {
      await this.cameraSession.start();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo captureSession start error: ${JSON.stringify(err)}`);
    }

    // 配置相机的参数可以调整拍照的一些功能,包括闪光灯、变焦、焦距等。
    this.configuringSession(this.cameraSession)
  }

  configuringSession(photoSession: camera.PhotoSession): void {
    // 判断设备是否支持闪光灯
    let flashStatus: boolean = false;
    try {
      flashStatus = photoSession.hasFlash();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to hasFlash. error: ${JSON.stringify(err)}`);
    }
    console.info(`CameraDemo Returned with the flash light support status: ${flashStatus}`);
    if (flashStatus) {
      // 判断是否支持自动闪光灯模式
      let flashModeStatus: boolean = false;
      try {
        let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
        flashModeStatus = status;
      } catch (error) {
        let err = error as BusinessError;
        console.error(`CameraDemo Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);
      }
      if (flashModeStatus) {
        // 设置自动闪光灯模式
        try {
          photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
        } catch (error) {
          let err = error as BusinessError;
          console.error(`CameraDemo Failed to set the flash mode. error: ${JSON.stringify(err)}`);
        }
      }
    }
    // 判断是否支持连续自动变焦模式
    let focusModeStatus: boolean = false;
    try {
      let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
      focusModeStatus = status;
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);
    }
    if (focusModeStatus) {
      // 设置连续自动变焦模式
      try {
        photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
      } catch (error) {
        let err = error as BusinessError;
        console.error(`CameraDemo Failed to set the focus mode. error: ${JSON.stringify(err)}`);
      }
    }
    // 获取相机支持的可变焦距比范围
    let zoomRatioRange: Array<number> = [];
    try {
      zoomRatioRange = photoSession.getZoomRatioRange();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);
    }
    if (zoomRatioRange.length <= 0) {
      return;
    }
    // 设置可变焦距比
    try {
      photoSession.setZoomRatio(zoomRatioRange[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);
    }
  }

  setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
    //设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中
    photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
      console.info(`CameraDemo getPhoto start. err: ${JSON.stringify(errCode)}`);
      if (errCode || photo === undefined || photo.main === undefined) {
        console.error('CameraDemo getPhoto failed');
        return;
      }
      let imageObj = photo.main;
      imageObj.getComponent(image.ComponentType.JPEG, async (errCode: BusinessError, component: image.Component): Promise<void> => {
        console.info('CameraDemo getComponent start');
        if (errCode || component === undefined) {
          console.error('CameraDemo getComponent failed');
          return;
        }
        let buffer: ArrayBuffer;
        if (component.byteBuffer) {
          buffer = component.byteBuffer;
          this.buffer = buffer;

          let sourceOptions: image.SourceOptions = {
            sourceDensity: 0, // 在不确定当前密度时传0
            sourcePixelFormat: image.PixelMapFormat.RGBA_8888,
            sourceSize: this.imageSize
          }
          let imageSource: image.ImageSource = image.createImageSource(buffer, sourceOptions);
          let opts: image.InitializationOptions = {
            editable: false,
            pixelFormat: image.PixelMapFormat.RGBA_8888,
            size: this.imageSize
          }
          let pixelMap = await imageSource.createPixelMap(opts);
          this.pixelMap = pixelMap;

          // 识别图片文字
          // this.textRecognitionTest(pixelMap);

        } else {
          console.error('CameraDemo byteBuffer is null');
          return;
        }
      });
    });
  }

  printCameraOutputCapability(cameraOutputCapability: camera.CameraOutputCapability) {
    let previewProfileArr: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
    let photoProfileArr: Array<camera.Profile> = cameraOutputCapability.photoProfiles;
    let videoProfileArr: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
    let supportedMetadataObjectTypeArr: Array<camera.MetadataObjectType> = cameraOutputCapability.supportedMetadataObjectTypes;
    previewProfileArr.forEach((value: camera.Profile, index: number) => {
      console.info(`CameraDemo 支持的预览尺寸: [${value.size.width},${value.size.height}]`);
    })
    photoProfileArr.forEach((value: camera.Profile, index: number) => {
      console.info(`CameraDemo 支持的拍照尺寸: [${value.size.width},${value.size.height}]`);
    })
    videoProfileArr.forEach((value: camera.VideoProfile, index: number) => {
      console.info(`CameraDemo 支持的录像尺寸: [${value.size.width},${value.size.height}], 支持的帧率范围: [${value.frameRateRange.min},${value.frameRateRange.max}]`);
    })
    supportedMetadataObjectTypeArr.forEach((value: camera.MetadataObjectType, index: number) => {
      console.info(`CameraDemo 支持的metadata流类型: ${value}`);
    })
  }
}
分享
微博
QQ
微信
回复
2025-01-10 09:30:41
相关问题
HarmonyOS 如何自定义相机背景
438浏览 • 1回复 待解决
加载页面的时候如何自定义header
1171浏览 • 1回复 待解决
HarmonyOS 弹框背景色如何自定义图片
309浏览 • 1回复 待解决
HarmonyOS 如何自定义相机
456浏览 • 1回复 待解决
HarmonyOS 自定义相机功能
551浏览 • 1回复 待解决
HarmonyOS 自定义相机demo
935浏览 • 1回复 待解决
HarmonyOS 自定义相机演示demo
621浏览 • 1回复 待解决
HarmonyOS 关于自定义相机功能
613浏览 • 1回复 待解决
HarmonyOS 自定义相机预览问题
541浏览 • 1回复 待解决