我正在完成这项任务,我们必须构建自定义相机功能并将图像存储到手机库中。所以我几乎一直做相机预览,但我还不确定如何使用swift 3捕获和存储图像。
这是源代码:
var captureSession = AVCaptureSession()
var sessionOutput = AVCapturePhotoOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
let deviceSession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDuoCamera,.builtInTelephotoCamera], mediaType: AVMediaTypeVideo, position: .unspecified)
for device in (deviceSession?.devices)! {
if device.position == AVCaptureDevicePosition.back {
do {
let input = try AVCaptureDeviceInput.init(device: device)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
if captureSession.canAddOutput(sessionOutput) {
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = .portrait
cameraLayerView.layer.addSublayer(previewLayer)
cameraLayerView.addSubview(topControllerView)
cameraLayerView.addSubview(bottomControllerView)
previewLayer.position = CGPoint(x: self.cameraLayerView.frame.width / 2, y: self.cameraLayerView.frame.height / 2)
previewLayer.bounds = cameraLayerView.frame
captureSession.startRunning()
}
}
} catch let avError {
print(avError)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
@IBAction func galleryAction(_ sender: UIButton) {
// This part shows the thumbnail of a current image been taken
}
@IBAction func captureAction(_ sender: UIButton) {
// This is the part i have capture the image
}
答案 0 :(得分:2)
拍摄照片非常简单,看看here。 要呈现图像选择器:
func takePhoto(sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
获取拍摄/选择的图像:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
现在,将UIImage保存到相册可以像解释here那样完成。 以下调用将照片保存到图库并调用完成处理程序:
UIImageWriteToSavedPhotosAlbum(yourImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
处理程序类似于:
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
// error
} else {
// no error
}
}