【发布时间】:2015-06-02 18:05:03
【问题描述】:
相机预览看起来很完美,但是当我拍照并将其保存到相机胶卷时,照片却显得非常暗。在这里尝试了一堆线程,但没有解决它。这是我的代码。
这设置了相机/预览并且工作正常:
captureSession.sessionPreset = AVCaptureSessionPreset640x480
let devices = AVCaptureDevice.devices()
// Loop through all the capture devices on this phone
for device in devices {
// Make sure this particular device supports video
if (device.hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the back camera
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
}
}
}
if captureDevice != nil {
beginSession()
}
func beginSession() {
var err : NSError? = nil
if captureSession.canAddInput(AVCaptureDeviceInput(device: captureDevice, error: &err)) {
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer)
self.view.bringSubviewToFront(cameraButton)
previewLayer?.frame = self.view.layer.frame
// start camera
captureSession.startRunning()
}
拍照时调用:
@IBAction func photoTaken(sender: UIButton) {
stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession.canAddOutput(stillImageOutput) {
captureSession.addOutput(stillImageOutput)
}
var videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
if videoConnection != nil {
// Show next step button
self.view.bringSubviewToFront(self.nextStep)
self.nextStep.hidden = false
// Secure image
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
self.image = UIImage(data: imageData)
}
// Freeze camera preview
captureSession.stopRunning()
}
}
当用户点击按钮继续拍摄照片后调用它(它现在将图像保存到相机胶卷,但当我让图像看起来不错时最终会做更多事情):
@IBAction func nextStepTapped(sender: UIButton) {
// Save to camera roll & proceeed
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil)
}
我的猜测是问题出在 photoTaken() 函数中,但我不知道。这是我第一次在 Swift/Xcode 中编写应用程序,因此将不胜感激。同样,问题是保存的照片非常暗,我已经尝试了几乎所有在互联网上可以找到的与此问题相关的东西,但没有任何效果。谢谢!
编辑:可能值得注意的是,我正在 iPhone 4S 上进行测试。会不会有什么关系?
【问题讨论】:
标签: ios swift camera avcapturesession