Taking photo with custom camera Swift 3
Thanks to Sharpkits I found my solution (This code works for me):
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
if let error = error {
print(error.localizedDescription)
}
if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer,
let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) {
let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: nil)
let dataProvider = CGDataProvider(data: imageData as! CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.absoluteColorimetric)
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
let cropedImage = self.cropToSquare(image: image)
let newImage = self.scaleImageWith(cropedImage, and: CGSize(width: 600, height: 600))
print(UIScreen.main.bounds.width)
self.tempImageView.image = newImage
self.tempImageView.isHidden = false
} else {
}
}
Swift 3 - Capturing a photo on custom camera view
set delegate to self and use this delegate AVCapturePhotoCaptureDelegate
And you can get captured image from below delegate
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: NSError?) {
if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) {
print(image: UIImage(data: dataImage).size)
}
}
Capture video using custom camera in ios swift3
Here is the code sample :
import UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate
{
var captureSession = AVCaptureSession()
var sessionOutput = AVCaptureStillImageOutput()
var movieOutput = AVCaptureMovieFileOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
var timer = Timer()
@IBOutlet var cameraView: UIView!
override func viewWillAppear(_ animated: Bool) {
self.cameraView = self.view
let session = AVCaptureDevice.DiscoverySession.init(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back)
let devices = session.devices
guard let audioDevice = AVCaptureDevice.default(for: .audio) else { return }
for device in devices
{
if device.position == AVCaptureDevice.Position.back
{
do{
let input = try AVCaptureDeviceInput(device: device )
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if captureSession.canAddInput(input){
captureSession.addInput(input)
captureSession.addInput(audioDeviceInput)
sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecType.jpeg]
if captureSession.canAddOutput(sessionOutput)
{
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer)
previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2)
previewLayer.bounds = cameraView.frame
}
captureSession.addOutput(movieOutput)
captureSession.startRunning()
self.handleCaptureSession()
}
}
catch{
print("Error")
}
}
}
}
func handleCaptureSession()
{
print("-----------Starting-----------")
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let dateFormatter : DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let fileName = dateString + "output.mov"
let fileUrl = paths[0].appendingPathComponent(fileName)
try? FileManager.default.removeItem(at: fileUrl)
self.movieOutput.startRecording(to: fileUrl, recordingDelegate: self)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute:
{
print("-----------Stopping-----------")
self.movieOutput.stopRecording()
})
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print("FINISHED \(error )")
// save video to camera roll
if error == nil {
print("---------------FilePath--------------\(outputFileURL.path)")
UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path, nil, nil, nil)
self.handleCaptureSession()
}
}
}
Related Topics
iOS 11 - Unable to Change Navigation Bar Height
Allow "Auto Lock" While Video Is Being Played
How to Detect Whether an iOS Device Is in Silent Mode or Not
Preventing Avcapturevideopreviewlayer from Rotating, But Allow UI Layer to Rotate with Orientation
Programmatically Detect Dark Mode in Swiftui to Display Appropriate Image
How to Add a Custom Separator to Uitableviewcell
Didbegincontact Is Being Called Multiple Times for the Same Skphysicsbody
Ios: Diddiscoverperipheral Not Called in Background Mode
How to Take Uiimage of Avcapturevideopreviewlayer Instead of Avcapturephotooutput Capture
How Can One Enable Keyboard Like in Imessages/Fb Messenger in Landscape Mode at iOS8
How to Detect the Scroll Direction from the Uicollectionview
Game Center Login Dialog Not Shown Again After Cancelling It for the First Time (Ios7)