You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS平台面向AI应用的相机分辨率获取与设置方法咨询

可通过代码直接获取/设置iOS相机分辨率

iOS的AVFoundation框架提供了两种主流的分辨率控制方式,你可以根据项目需求选择:

方式1:使用AVCaptureSession预设分辨率(最简单)

系统预设了常用的分辨率档位,无需手动匹配设备支持格式,直接设置session的sessionPreset属性即可,建议在添加输入流之前完成设置。
常用预设选项:

  • .photo:设备支持的最高拍照分辨率,适合静态图像采集场景
  • .hd1920x1080:1080P分辨率,平衡清晰度和推理性能,是AI实时图像处理的常用选择
  • .hd1280x720:720P分辨率,性能开销更低,适合轻量模型推理
  • .vga640x480:VGA分辨率,适合低算力设备的极简推理场景

设置前可以提前校验当前设备是否支持该预设:

if session.canSetSessionPreset(.hd1920x1080) {
    session.sessionPreset = .hd1920x1080
}

方式2:自定义设置设备分辨率(灵活度最高)

如果预设档位无法满足你的特殊尺寸要求,可以直接遍历AVCaptureDevice支持的所有格式,匹配到目标分辨率后设置为activeFormat即可。
注意修改设备配置必须包裹在lockForConfiguration和unlockForConfiguration之间,否则会触发崩溃。示例代码:

guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return }
do {
    try camera.lockForConfiguration()
    // 遍历所有设备支持的格式
    for format in camera.formats {
        let dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
        // 匹配你需要的目标分辨率,示例为1280*720
        if dimensions.width == 1280 && dimensions.height == 720 {
            camera.activeFormat = format
            break
        }
    }
    camera.unlockForConfiguration()
} catch {
    print("配置相机分辨率失败:\(error.localizedDescription)")
}

获取当前相机分辨率

直接读取设备当前激活格式的尺寸参数即可:

let currentFormat = camera.activeFormat
let dimensions = CMVideoFormatDescriptionGetDimensions(currentFormat.formatDescription)
print("当前相机分辨率:\(dimensions.width) * \(dimensions.height)")

针对你现有代码的修改示例

private func addVideoDeviceInput() -> Bool {
    /**Tries to get the default back camera.
     */
    guard let camera  = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
        return false
    }
    do {
        // 新增分辨率设置逻辑,这里以1080P预设为例
        try camera.lockForConfiguration()
        if session.canSetSessionPreset(.hd1920x1080) {
            session.sessionPreset = .hd1920x1080
        }
        camera.unlockForConfiguration()
        
        let videoDeviceInput = try AVCaptureDeviceInput(device: camera)
        if session.canAddInput(videoDeviceInput) {
            session.addInput(videoDeviceInput)
            return true
        }
        else {
            return false
        }
    }
    catch {
        fatalError("Cannot create video device input: \(error.localizedDescription)")
    }
}

内容的提问来源于stack exchange,提问作者El_Loco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:45:03