我制作了一个简单的iOS应用程序,可以拍摄照片并将其保存到设备的库中。我期待一个风景图像作为输出,但相机产生的是一个风景图像的纵向,比如50x100,图像旋转到90度。我希望图像是横向的,我不确定我的代码有什么问题。
我需要将预览图层设置为横向,因此我将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!)!)
})
}
答案 0 :(得分:3)
我明白了!所以在将图像保存到库之前,你必须根据预览图层上的内容设置输出的方向,只需添加以下行:
videoConnection.videoOrientation = .landscapeRight
...
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)
})
}