用相机应用程序拍摄方形照片

时间:2018-04-02 10:39:06

标签: swift avfoundation avcapturesession

我目前正在构建一个相机应用程序,并希望让相机拍摄像Instagram一样的方形图像375x375并保存它。

我能够取消相机的取景器,但它没有以正确的方式拍摄照片,而且当我保存它时它会将其保存在全景中。我环顾了另一个Q& As那里,但它们似乎都不适合我的代码。

有人可以帮我解决这个问题。

import Foundation
import UIKit
import AVFoundation

class CameraViewController: UIViewController{

var captureSession = AVCaptureSession()
var frontCameraDeviceInput: AVCaptureDeviceInput?
var backCameraDeviceInput: AVCaptureDeviceInput?
var currentCamera: AVCaptureDevice?

var photoOutput: AVCapturePhotoOutput?

var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

var image: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    setupCaptureSession()
    setupDevice()
    setupInputOutput()
    setupPreviewLayer()
    startRunningCaptureSession()
}

func setupCaptureSession() {
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
}

func setupDevice() {
    let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front)
    let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)

    frontCameraDeviceInput = try? AVCaptureDeviceInput(device: frontCamera!)
    backCameraDeviceInput = try? AVCaptureDeviceInput(device: backCamera!)
}

func setupInputOutput() {
    captureSession.addInput(backCameraDeviceInput!)
    photoOutput = AVCapturePhotoOutput()
    photoOutput?.isHighResolutionCaptureEnabled = true
    photoOutput?.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format:[AVVideoCodecKey: AVVideoCodecType.jpeg])], completionHandler: nil)
    captureSession.addOutput(photoOutput!)
}

func setupPreviewLayer() {
    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
    cameraPreviewLayer?.frame = self.view.frame
    self.view.layer.insertSublayer(cameraPreviewLayer!, at: 0)
}

func startRunningCaptureSession() {
    captureSession.startRunning()
}

@IBAction func camerButton(_ sender: Any) {
    let settings = AVCapturePhotoSettings()
    photoOutput?.capturePhoto(with: settings, delegate: self)
}

@IBAction func switchCamera(_ sender: Any) {
    captureSession.beginConfiguration()
    //Change camera device inputs from back to front or opposite
    if captureSession.inputs.contains(frontCameraDeviceInput!) == true {
        captureSession.removeInput(frontCameraDeviceInput!)
        captureSession.addInput(backCameraDeviceInput!)
    } else if captureSession.inputs.contains(backCameraDeviceInput!) == true {
        captureSession.removeInput(backCameraDeviceInput!)
        captureSession.addInput(frontCameraDeviceInput!)
    }

    //Commit all the configuration changes at once
    captureSession.commitConfiguration();
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "previewCameraPhoto" {
        let previewVC = segue.destination as! PreviewViewController
        previewVC.image = self.image
    }
}
}

extension CameraViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    if let imageData = photo.fileDataRepresentation() {
        image = UIImage(data: imageData)
        performSegue(withIdentifier: "previewCameraPhoto", sender: nil)
    }
}

override var prefersStatusBarHidden: Bool
{
    return true
}
}

2 个答案:

答案 0 :(得分:2)

以下代码行用于捕获Image。点击捕获按钮时执行它们。在你的情况下它是

  

func camerButton(_ sender:Any)

所用方法的定义如下。

DispatchQueue.global(qos: .default).async {
            let videoConnection = self.imageOutput.connection(with: AVMediaType.video)
            let orientation: UIDeviceOrientation = UIDevice.current.orientation
            switch orientation {
            case .portrait:
                videoConnection?.videoOrientation = .portrait
            case .portraitUpsideDown:
                videoConnection?.videoOrientation = .portraitUpsideDown
            case .landscapeRight:
                videoConnection?.videoOrientation = .landscapeLeft
            case .landscapeLeft:
                videoConnection?.videoOrientation = .landscapeRight
            default:
                videoConnection?.videoOrientation = .portrait
            }

            self.imageOutput.captureStillImageAsynchronously(from: videoConnection!) { buffer, _ in
                self.session.stopRunning()

                guard let b = buffer
                    else { return }

                let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(b)

                if var image = UIImage(data: data!) {

                    // Crop the image if the output needs to be square.
                    if self.configuration.onlySquareImagesFromCamera {
                        image = self.cropImageToSquare(image)
                    }

                    // Flip image if taken form the front camera.
                    if let device = self.device, device.position == .front {
                        image = self.flipImage(image: image)
                    }

                    DispatchQueue.main.async {
                        self.didCapturePhoto?(image)
                    }
                }
            }
        }

此功能使用的两种方法 -

func cropImageToSquare(_ image: UIImage) -> UIImage {
            let orientation: UIDeviceOrientation = UIDevice.current.orientation
            var imageWidth = image.size.width
            var imageHeight = image.size.height
            switch orientation {
            case .landscapeLeft, .landscapeRight:
                // Swap width and height if orientation is landscape
                imageWidth = image.size.height
                imageHeight = image.size.width
            default:
                break
            }

            // The center coordinate along Y axis
            let rcy = imageHeight * 0.5
            let rect = CGRect(x: rcy - imageWidth * 0.5, y: 0, width: imageWidth, height: imageWidth)
            let imageRef = image.cgImage?.cropping(to: rect)
            return UIImage(cgImage: imageRef!, scale: 1.0, orientation: image.imageOrientation)
        }


// Used when image is taken from the front camera.
func flipImage(image: UIImage!) -> UIImage! {
        let imageSize: CGSize = image.size
        UIGraphicsBeginImageContextWithOptions(imageSize, true, 1.0)
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.rotate(by: CGFloat(Double.pi/2.0))
        ctx.translateBy(x: 0, y: -imageSize.width)
        ctx.scaleBy(x: imageSize.height/imageSize.width, y: imageSize.width/imageSize.height)
        ctx.draw(image.cgImage!, in: CGRect(x: 0.0,
                                            y: 0.0,
                                            width: imageSize.width,
                                            height: imageSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
}

我不应忘记赞扬这个图书馆的开发者 - https://github.com/Yummypets/YPImagePicker/blob/2.5.1/Source/Camera/YPCameraVC.swift

答案 1 :(得分:0)

只需将其添加到图像选择器中,用户就可以选择其首选裁剪比例。默认将是你想要的..一个方形照片

self.ImagePicker.allowsEditing = true

相关问题