Creating Thumbnail from Local Video in Swift

Creating thumbnail from local video in swift

Translated with some edits from:

First frame of a video using AVFoundation

    var err: NSError? = nil
let asset = AVURLAsset(URL: NSURL(fileURLWithPath: "/that/long/path"), options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
let cgImage = imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil, error: &err)
// !! check the error before proceeding
let uiImage = UIImage(CGImage: cgImage)
let imageView = UIImageView(image: uiImage)
// lay out this image view, or if it already exists, set its image property to uiImage

How to Create thumbnail from local files

After a lot of search, I found this solution :

import PDFKit
import AVKit
import WebKit

func createThumb() {
let url = URL(string: (self.file?.path()))
switch file?.type {
case: FileType.image.rawValue:
let image = UIImage(contentsOfFile: (url?.path)!)
_finalImage = self.createScaledImage(image: image!)
break
case: FileType.office.rawValue:
//Loading.......
break
case FileType.Pdf.rawValue:
guard let doc = PDFDocument(url: url!) else {return}
guard let page = doc.page(at: 0) else {return}
_finalImage = page.thumbnail(of: CGSize(width: 768, height: 1024), for: .cropBox)
break
case: FileType.video.rawValue:
let asset = AVAsset(url: url!)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
let time = CMTime(seconds: 2, preferredTimescale: 1)
do {
let imageRef = try imageGenerator.copyCGImage(at: time, actualTime: nil)
_finalImage = UIImage(cgImage: imageRef)
} catch let error{
print("Error: \(error)")
}
break

}
}

func createScaledImage(image: UIImage) {

let THUMB_WIDTH = 150.0 - 40.0
let THUMB_HEIGHT = THUMB_WIDTH - 23.0
var itemThumb = resizeImage(image: image, constraintSize: CGSize(width: THUMB_WIDTH, height: THUMB_HEIGHT))
let thumbRect = CGRect(x: 0, y: 0, width: 10, height: 10)
UIGraphicsBeginImageContextWithOptions(thumbRect.size, true, 0.0)
let context = UIGraphicsGetCurrentContext()

// Fill a white rect
context?.setFillColor(gray: 1.0, alpha: 1.0)
context?.fill(thumbRect)

// Stroke a gray rect
let comps : [CGFloat] = [0.8, 0.8, 0.8, 1]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let strokeColor = CGColor(colorSpace: colorSpace, components: comps)
context?.setStrokeColor(strokeColor!)
UIRectFrame(thumbRect)
//CGColorRelease(strokeColor!)

itemThumb.draw(in: thumbRect.insetBy(dx: 1, dy: 1))

itemThumb = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.finishThumCreation(image: image)
}
}

Getting a thumbnail from a video url or data in iOS

The answer to this question is that one can now with 4.0 iOS get thumbnails using AVFoundation, the following code where the class property url is the movie url, will do the trick (you can get the thumbnail at any time, in the example its at time 0)

-(void)generateImage
{
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);

AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(@"couldn't generate thumbnail, error:%@", error);
}
[button setImage:[UIImage imageWithCGImage:im] forState:UIControlStateNormal];
thumbImg=[[UIImage imageWithCGImage:im] retain];
[generator release];
};

CGSize maxSize = CGSizeMake(320, 180);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];

}

How to get thumbnail image of video picked from UIPickerViewController in Swift?

The simplest answer:

import AVFoundation

private func thumbnailForVideoAtURL(url: NSURL) -> UIImage? {

let asset = AVAsset(URL: url)
let assetImageGenerator = AVAssetImageGenerator(asset: asset)

var time = asset.duration
time.value = min(time.value, 2)

do {
let imageRef = try assetImageGenerator.copyCGImageAtTime(time, actualTime: nil)
return UIImage(CGImage: imageRef)
} catch {
print("error")
return nil
}
}


Related Topics



Leave a reply



Submit