import camera from '@ohos.multimedia.camera'

import camera from '@ohos.multimedia.camera'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
import { MLog } from '@ohos/ts-core-lib'; 
 
 
const TAG = "camera-capture" 
 
export class CameraCapture { 
  private cameraManager?: camera.CameraManager 
  private fontCamera?: camera.CameraDevice //前置 
  private backCamera?: camera.CameraDevice //后置 
  private surfaceId: string = "" 
  private profile?: camera.Profile 
  private photoOuput?: camera.PhotoOutput 
  private cameraInput?: camera.CameraInput 
  private  session?: camera.Session 
  private previewOutput?: camera.PreviewOutput 
 
  async init(surfaceId: string) { 
    try { 
      this.cameraManager = camera.getCameraManager(getContext(this)) 
      this.cameraManager.on('cameraStatus', (data) => { 
        MLog.d(TAG, "cameraStatus", data) 
      }) 
      let muted = this.cameraManager.isCameraMuted() 
      if (muted) { 
        MLog.i(TAG, "相机被禁用") 
        return 
      } 
      this.surfaceId = surfaceId 
      let cameras = this.cameraManager.getSupportedCameras() 
      //查找前置相机和后置相机 
      cameras.forEach(item => { 
        if (item.cameraPosition == camera.CameraPosition.CAMERA_POSITION_BACK) { 
          this.backCamera = item 
        } else if (item.cameraPosition == camera.CameraPosition.CAMERA_POSITION_FRONT) { 
          this.fontCamera = item 
        } 
      }) 
 
      //profile 输出配置 
      let data = this.getSupportedOutputCapability(this.fontCamera!, this.cameraManager!, camera.SceneMode.NORMAL_PHOTO) 
      this.profile = data.previewProfiles[0] 
      //创建 输入 输出 预览 
      this.cameraInput = this.createInput(this.cameraManager, this.fontCamera!) 
      this.cameraInput?.on('error', this.fontCamera, (err) => { 
        MLog.d(TAG, "cameraInput error", err) 
      }) 
      this.photoOuput = this.createOutputPhoto(this.cameraManager, this.profile) 
      this.previewOutput = this.createPreview(this.cameraManager, this.profile) 
 
      this.session = this.cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) 
 
      this.session.beginConfig() 
      this.session.addInput(this.cameraInput) 
      this.session.addOutput(this.previewOutput) 
      this.session.addOutput(this.photoOuput) 
      this.session.commitConfig() 
      this.session?.start() 
    } catch (e) { 
      MLog.i(TAG, "The getCameraManager call failed. error code", e) 
    } 
  } 
 
  async start() { 
    // this.session?.start() 
  } 
 
  async capture() { 
    await this.photoOuput?.capture() 
  } 
 
  async stop() { 
    await this.session?.stop() 
  } 
 
  async release() { 
    await this.cameraInput?.close() 
    await this.photoOuput?.release() 
    await this.previewOutput?.release() 
    await this.session?.stop() 
    await this.session?.release() 
  } 
 
  private createInput(cameraManager: camera.CameraManager, device: camera.CameraDevice) { 
    let cameraInput: camera.CameraInput | undefined = undefined; 
    try { 
      cameraInput = cameraManager.createCameraInput(device); 
    } catch (error) { 
      // 失败返回错误码error.code并处理 
      let err = error as BusinessError; 
      MLog.e(TAG, `The createCameraInput call failed. error code: ${err.code}`); 
    } 
    return cameraInput; 
  } 
 
  private createPreview(cameraManager: camera.CameraManager, profile: camera.Profile) { 
    let previewOutput: camera.PreviewOutput | undefined = undefined; 
    try { 
      previewOutput = cameraManager.createPreviewOutput(profile, this.surfaceId); 
    } catch (error) { 
      // 失败返回错误码error.code并处理 
      let err = error as BusinessError; 
      MLog.e(TAG, `The createCameraInput call failed. error code: ${err.code}`); 
    } 
    return previewOutput; 
  } 
 
  private createOutputPhoto(cameraManager: camera.CameraManager, profile: camera.Profile): camera.PhotoOutput | undefined { 
    let photoOutput: camera.PhotoOutput | undefined 
    try { 
      photoOutput = cameraManager.createPhotoOutput(profile); 
    } catch (error) { 
      // 失败返回错误码error.code并处理 
      let err = error as BusinessError; 
      MLog.e(TAG, `The createPhotoOutput call failed. error code: ${err.code}`); 
    } 
    return photoOutput; 
  } 
 
  getSupportedOutputCapability(camera: camera.CameraDevice, cameraManager: camera.CameraManager, sceneMode: camera.SceneMode): camera.CameraOutputCapability { 
    let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(camera, sceneMode); 
    return cameraOutputCapability; 
  } 
}

预览是黑屏的。

HarmonyOS
2024-11-13 11:51:21
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

参考以下demo:

// CameraCapture.ets 
import camera from '@ohos.multimedia.camera'; 
 
export class CameraCapture { 
  private cameraManager?: camera.CameraManager 
  private fontCamera?: camera.CameraDevice //前置 
  private backCamera?: camera.CameraDevice //后置 
  private surfaceId: string = "" 
  private session?: camera.Session 
  private photoOuput?: camera.PhotoOutput 
  private cameraInput?: camera.CameraInput 
  private previewOutput?: camera.PreviewOutput 
 
  async init(surfaceId: string): Promise<void> { 
    this.surfaceId = surfaceId 
    try { 
      // 释放会话及其相关参数 
      await this.releaseCamera(); 
      // 获取相机管理器实例 
      this.cameraManager = camera.getCameraManager(getContext(this)); 
 
      let muted = this.cameraManager.isCameraMuted() 
      if (muted) { 
        return 
      } 
 
      // 获取支持指定的相机设备对象 
      let cameras = this.cameraManager.getSupportedCameras() 
      //查找前置相机和后置相机 
      cameras.forEach(item => { 
        if (item.cameraPosition == camera.CameraPosition.CAMERA_POSITION_BACK) { 
          this.backCamera = item 
        } else if (item.cameraPosition == camera.CameraPosition.CAMERA_POSITION_FRONT) { 
          this.fontCamera = item 
        } 
      }) 
      let profiles = this.cameraManager.getSupportedOutputCapability(this.backCamera, camera.SceneMode.NORMAL_PHOTO); 
      let previewProfiles: Array<camera.Profile> = profiles.previewProfiles; 
      let photoProfiles: Array<camera.Profile> = profiles.photoProfiles; 
 
      // 创建previewOutput输出对象 
      this.previewOutput = this.cameraManager.createPreviewOutput(previewProfiles[0], this.surfaceId); 
      // 创建photoOutPut输出对象 
      this.photoOuput = this.cameraManager.createPhotoOutput(photoProfiles[0]); 
      // 创建cameraInput输出对象 
      this.cameraInput = this.cameraManager.createCameraInput(this.backCamera); 
 
      // 打开相机 
      await this.cameraInput.open(); 
 
      // 会话流程 
      // 创建CaptureSession实例 
      this.session = this.cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO); 
      // 开始配置会话 
      this.session.beginConfig(); 
      // 把CameraInput加入到会话 
      this.session.addInput(this.cameraInput); 
      // 把previewOutput加入到会话 
      this.session.addOutput(this.previewOutput); 
      // 把photoOutPut加入到会话 
      this.session.addOutput(this.photoOuput); 
      // 提交配置信息 
      await this.session.commitConfig(); 
      // 开始会话工作 
      await this.session.start(); 
 
      this.cameraManager.on('cameraStatus', (data) => {}) 
    } catch (e) { 
    } 
  } 
 
  async releaseCamera(): Promise<void> { 
    if (this.previewOutput) { 
      try { 
        await this.previewOutput.release(); 
      } catch (error) { 
      } finally { 
        this.previewOutput = undefined; 
      } 
    } 
    if (this.photoOuput) { 
      try { 
        await this.photoOuput.release(); 
      } catch (error) { 
      } finally { 
        this.photoOuput = undefined; 
      } 
    } 
    if (this.session) { 
      try { 
        await this.session.release(); 
      } catch (error) { 
      } finally { 
        this.session = undefined; 
      } 
    } 
    if (this.cameraInput) { 
      try { 
        await this.cameraInput.close(); 
      } catch (error) { 
      } finally { 
        this.cameraInput = undefined; 
      } 
    } 
  } 
}
// 测试页面CameraView.ets 
 
import { CameraCapture } from '../viewmodel/CameraCaputre' 
import { abilityAccessCtrl, common } from '@kit.AbilityKit'; 
 
@Entry 
@Component 
struct CameraView { 
  private camera?: CameraCapture 
  private controller: XComponentController = new XComponentController() 
  private surfaceId: string = ''; 
  @State userGrant: boolean = false 
  async aboutToAppear() { 
    await this.requestCameraPermission() 
  } 
 
  async reqPermissionsFromUser(): Promise<number[]> { 
    let context = getContext() as common.UIAbilityContext; 
    let atManager = abilityAccessCtrl.createAtManager(); 
    let grantStatus = await atManager.requestPermissionsFromUser(context, [ 
      'ohos.permission.CAMERA', 
    ]); 
    return grantStatus.authResults; 
  } 
 
  // 申请相机权限 
  async requestCameraPermission() { 
    let grantStatus = await this.reqPermissionsFromUser() 
    for (let i = 0; i < grantStatus.length; i++) { 
      if (grantStatus[i] === 0) { 
        // 用户授权,可以继续访问目标操作 
        this.userGrant = true; 
      } 
    } 
  } 
 
  build() { 
    Column() { 
      Text('相机') 
      if (this.userGrant) { 
        Row() { 
          XComponent({ 
            id: 'componentId', 
            type: 'surface', 
            controller: this.controller 
          }) 
            .onLoad(async () => { 
              this.surfaceId = this.controller.getXComponentSurfaceId(); 
              this.camera = new CameraCapture() 
              await this.camera?.init(this.surfaceId) 
            }) 
            .size({ 
              width: 384, 
              height: 500 
            }) 
            .margin({ bottom: 40 }) 
        } 
      } 
    } 
  } 
}
分享
微博
QQ
微信
回复
2024-11-13 17:01:12
相关问题
import asset from '@ohos.security.asset'报错
2162浏览 • 1回复 待解决
OpenHarmony 3.0 LTS camera驱动
4132浏览 • 0回复 待解决
camera 获取预览数据
1801浏览 • 1回复 待解决
HarmonyOS camera设置对焦无效果
365浏览 • 1回复 待解决
OpenHarmony camera sensor调试疑问
1825浏览 • 0回复 待解决
camera_lite预览功能如何实现?
2360浏览 • 0回复 待解决
ndk中没有native camera对应头文件
1858浏览 • 1回复 待解决
关于鸿蒙camera外设的驱动编写疑问
4535浏览 • 1回复 待解决
HarmonyOS Camera_CaptureSession 能不能重用
375浏览 • 1回复 待解决
HarmonyOS Camera录制视频如何适配竖屏
130浏览 • 0回复 待解决
camera demo可执行文件编译
4111浏览 • 0回复 待解决