Francisco Escobar
Francisco Escobar

Reputation: 241

crop an image taken with the camera in swift

I have an app where the user can take a picture, but i need save only the area of the UIView that i used as a mask (with a clear background), when i try to do the cropping this is doing it wrong, i suspect that the image is bigger than the screen and the cropped area it's working good but in reference of the image instead of the screen area.

This my code: (cameraFrame is the mask view)

if let videoConnection = output.connectionWithMediaType(AVMediaTypeVideo) {
            output.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
                var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                var dataProvider = CGDataProviderCreateWithCFData(imageData)
                var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)

                var cropped = CGImageCreateWithImageInRect(cgImageRef, self.cameraFrame.frame)
                self.imagen = UIImage(CGImage: cropped, scale: 1.0, orientation: UIImageOrientation.Right)
                self.performSegueWithIdentifier("aImagen", sender: self)
            })
        }

this is the app running: enter image description here

Upvotes: 2

Views: 3176

Answers (1)

Vinod Joshi
Vinod Joshi

Reputation: 7852

I am using following pod

https://github.com/AlexLittlejohn/ALCameraViewController

usage

let croppingEnabled = true
let cameraViewController = ALCameraViewController(croppingEnabled: croppingEnabled) { image in
    // Do something with your image here. 
    // If cropping is enabled this image will be the cropped version
}

presentViewController(cameraViewController, animated: true, completion: nil)

Upvotes: 1

Related Questions