斯威夫特3 AVCaptureSession图像输出是在纵向而非横向
问题描述:
我做了一个简单的iOS应用程序,所拍摄照片并将其保存到该设备的图书馆。我期待风景图像输出,但什么是相机生产是一个风景图像的纵向,说一个50×,图像旋转到90度。我希望图像处于风景中,我不确定我的代码有什么问题。斯威夫特3 AVCaptureSession图像输出是在纵向而非横向
我需要我的预览层是在景观,所以我把我的AVCaptureVideoOrientation到所需方向。
previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
下面是配置:
override func viewWillAppear(_ animated: Bool) {
let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
for device in devices! {
if (device as AnyObject).position == AVCaptureDevicePosition.back {
do {
let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice)
if (captureSession.canAddInput(input)) {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
captureSession.addInput(input)
sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession.canAddOutput(sessionOutput)) {
captureSession.addOutput(sessionOutput)
captureSession.startRunning()
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResize
previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
previewLayer.frame = self.cameraView.bounds
cameraView.layer.addSublayer(previewLayer)
previewLayer.position = CGPoint(x: self.cameraView.frame.width/2, y: self.cameraView.frame.height/2)
previewLayer.bounds = cameraView.frame
cameraView.addSubview(captureBtn)
cameraView.addSubview(shutterTimer)
}
}
} catch let err {
print(err)
return
}
}
}
}
图像输出
if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo) {
sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (buffer, error) in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let image = UIImage(data: imageData!)!
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
print(UIImage(data: imageData!)!)
})
}
答
我知道了!所以,如果你的图像保存到库中,你必须设置输出的方向
videoConnection.videoOrientation = .landscapeRight
:通过简单地加入这一行根据您预览层上有什么0
....
if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo) {
// set output orientation before saving
videoConnection.videoOrientation = .landscapeRight
sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (buffer, error) in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let image = UIImage(data: imageData!)!
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
})
}