Last active
June 27, 2021 11:59
-
-
Save sketchytech/a4e615c8c895c6500cf4 to your computer and use it in GitHub Desktop.
Capture Still Images from Video and add to a View: Swift 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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