Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active June 27, 2021 11:59
Show Gist options
  • Save sketchytech/a4e615c8c895c6500cf4 to your computer and use it in GitHub Desktop.
Save sketchytech/a4e615c8c895c6500cf4 to your computer and use it in GitHub Desktop.
Capture Still Images from Video and add to a View: Swift 2
// MARK: THANKS TO: http://stackoverflow.com/questions/4294996/get-uiimage-from-the-calayer-attached-to-avplayer-extract-frame-from-video-play
func finshedCapture(im:CGImage?, view:UIView, error:NSError?) {
if let img = im {
print("OK")
addImageViewWithImage(img, toView: view)
}
else {
print("Fail")
}
}
func addImageViewWithImage(img: CGImage, toView view:UIView) {
dispatch_async(dispatch_get_main_queue(), {
let imgView = UIImageView(image: UIImage(CGImage: img))
view.addSubview(imgView)
})
}
// MARK: THANKS TO: http://stackoverflow.com/questions/4001755/trying-to-understand-cmtime-and-cmtimemake
func captureFrame(url:NSURL, timeInSeconds time:Int64, addToView view:UIView) {
let generator = AVAssetImageGenerator(asset: AVAsset(URL: url))
let tVal = NSValue(CMTime: CMTimeMake(time, 1))
generator.generateCGImagesAsynchronouslyForTimes([tVal], completionHandler: {(_, im:CGImage?, _, _, e:NSError?) in finshedCapture(im, view:view, error:e)})}
// implementation
if let url = NSBundle.mainBundle().URLForResource("MYMOVIE", withExtension: "MP4") {
captureFrame(url, timeInSeconds: 12, addToView:self.view)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment