问题描述
我正在使用 AVCapturePhotoOutput
用相机拍照。但是,与预览视频源相比,拍摄的照片有时(约 50% 的时间)会略微向下偏移。
以下是我设置视频源的方法:
let avSession = AVCaptureSession()
let photoOutput = AVCapturePhotoOutput()
override func viewDidLoad() {
super.viewDidLoad()
let cameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera,for: .video,position: .back)!
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: cameraDevice)
if avSession.canAddInput(captureDeviceInput) {
avSession.addInput(captureDeviceInput)
avSession.sessionPreset = .photo
}
if avSession.canAddOutput(photoOutput) {
avSession.addOutput(photoOutput)
}
} catch {
print("Error: \(error)")
}
previewView.videoPreviewLayer.frame = view.layer.bounds
previewView.videoPreviewLayer.videoGravity = .resizeAspectFill
previewView.session = self.avSession
avSession.startRunning() /// start the session
outputimageView.alpha = 0 /// hide image view
}
这会按预期生成实时视频预览。接下来,我使用 capturePhoto(with:delegate:)
拍照:
let photoSettings = AVCapturePhotoSettings()
if let photoPreviewType = photoSettings.availablePreviewPhotoPixelFormatTypes.first {
photoSettings.previewPhotoFormat = [kCVPixelBufferPixelFormatTypeKey as String: photoPreviewType]
photoOutput.capturePhoto(with: photoSettings,delegate: self)
}
/// get the image from `capturePhoto`
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput,didFinishProcessingPhoto photo: AVCapturePhoto,error: Error?) {
if let imageData = photo.fileDataRepresentation() {
let previewImage = UIImage(data: imageData)
outputimageView.image = previewImage
outputimageView.alpha = 1
}
}
}
结果 (video version here):
我怎样才能摆脱这种偏移?我希望来自 capturePhoto
的照片尽可能与视频提要相符。我还看到了 this question,这似乎是一个类似的问题,但它已经超过 6 年了,解决方案不起作用。
Full demo project of the problem
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)