Swift 3 un-flip 前置摄像头图片

Posted

技术标签:

【中文标题】Swift 3 un-flip 前置摄像头图片【英文标题】:Swift 3 un-flip front camera pictures 【发布时间】:2017-03-31 17:12:45 【问题描述】:

我的前置摄像头有问题,它会因为某种原因翻转图片。我尝试使用imageView.transform = CGAffineTransform(scaleX: -1, y: 1) 来避免这个问题并且它奏效了。但我意识到我也在翻转后置摄像头。有什么解决办法吗?

ImagePreviewViewController:

    @IBAction func close(_ sender: Any) 

    let cameraViewController = storyboard?.instantiateViewController(withIdentifier: "CameraViewController") as! CameraViewController
    navigationController?.pushViewController(cameraViewController, animated: true)


@IBOutlet weak var close: UIButton!
var capturedImage : UIImage?

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() 
    super.viewDidLoad()
    imageView.image = capturedImage
            close.setImage(UIImage(named: "Close.png"), for: UIControlState.normal)
    //imageView.transform = CGAffineTransform(scaleX: -1, y: 1)

CameraViewController:

@IBOutlet var cameraView: UIView!
let session = AVCaptureSession()
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()
var camera : AVCaptureDevice?
var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
var cameraCaptureOutput : AVCapturePhotoOutput?
var frontCamera: Bool = false

override func viewDidLoad() 
    super.viewDidLoad()
    session.sessionPreset = AVCaptureSessionPresetPhoto
    frontCamera(frontCamera)
        if camera != nil

            beginSession()

    
    initializeCaptureSession()
    shoot.setImage(UIImage(named: "Shoot.png"), for: UIControlState.normal)
    // Do any additional setup after loading the view, typically from a nib.


func beginSession()

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    self.cameraView.layer.addSublayer(cameraPreviewLayer!)
    cameraPreviewLayer?.frame = self.cameraView.layer.bounds
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    session.startRunning()
    stillImageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
    if session.canAddOutput(stillImageOutput)
        session.addOutput(stillImageOutput)

    


func frontCamera(_ front: Bool)

    let devices = AVCaptureDevice.devices()

    do

        try session.removeInput(AVCaptureDeviceInput(device: camera))

     catch 

        print("error")
    

    for device in devices!

        if((device as AnyObject).hasMediaType(AVMediaTypeVideo)) 
            if front
                if (device as AnyObject).position == AVCaptureDevicePosition.front 

                    camera = device as? AVCaptureDevice

                    do
                        try session.addInput(AVCaptureDeviceInput(device: camera))
                     catch 


                    
                    break

                    
             else 


            
            



    


func displayCapturedPhoto(capturedPhoto : UIImage) 

    let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "ImagePreviewViewController") as! ImagePreviewViewController
    imagePreviewViewController.capturedImage = capturedPhoto
    navigationController?.pushViewController(imagePreviewViewController, animated: true)



@IBOutlet weak var shoot: UIButton!
@IBAction func takePicture(_ sender: Any) 

    takePicture()



func initializeCaptureSession() 

    session.sessionPreset = AVCaptureSessionPresetHigh
    camera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    do 
        let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!)
        cameraCaptureOutput = AVCapturePhotoOutput()

        session.addInput(cameraCaptureInput)
        session.addOutput(cameraCaptureOutput)

     catch 
        print(error.localizedDescription)
    

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    cameraPreviewLayer?.frame = view.bounds
    cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait

    view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

    session.startRunning()


func takePicture() 
    let settings = AVCapturePhotoSettings()
    settings.flashMode = .off
    cameraCaptureOutput?.capturePhoto(with: settings, delegate: self as AVCapturePhotoCaptureDelegate)



@IBOutlet weak var flash: UIButton!
@IBAction func flash(_ sender: Any) 



    

@IBAction func switchCamera(_ sender: Any) 

    frontCamera = !frontCamera
    session.beginConfiguration()
    let inputs = session.inputs as! [AVCaptureInput]
    for oldInput: AVCaptureInput in inputs
        session.removeInput(oldInput)

    
    frontCamera(frontCamera)

    session.commitConfiguration()

扩展 CameraViewController : AVCapturePhotoCaptureDelegate

func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) 

    if let unwrappedError = error 
        print(unwrappedError.localizedDescription)
     else 

        if let sampleBuffer = photoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) 

            if let finalImage = UIImage(data: dataImage) 

                displayCapturedPhoto(capturedPhoto: finalImage)
            
        
    


override var prefersStatusBarHidden: Bool 
    return true

【问题讨论】:

imageView的内容怎么设置? “有什么解决办法吗?”有代码吗? 我添加了CameraViewController代码和ImagePreviewViewController。谢谢你们。 【参考方案1】:

尝试将连接的 isVideoMirrored 属性设置为 true。这将翻转图像。

func initializeCaptureSession() 

...

cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraPreviewLayer?.frame = view.bounds
cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraPreviewLayer?.connection.isVideoMirrored = true

view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

session.startRunning()

【讨论】:

以上是关于Swift 3 un-flip 前置摄像头图片的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 swift avfoundation 设置前置摄像头变焦

Swift 2.0 Xcode 7.1 图像选择器前置摄像头图像在选择时旋转

使用前置摄像头时需要镜像视频方向和手柄旋转

c#利用AForge来进行摄像头拍照功能。请问可否设置保存图片的大小。

切换到前置摄像头时 AVFoundation 摄像头崩溃(刷新摄像头)

C# 获取普通USB摄像头的像素数据,并将还原成图片。。。