Code snippet: How to generate video thumbnail

DannyCDannyC US ✭✭✭✭

Wanted to share a code snippet to generate a video thumbnail. Hope it helps someone looking to do the same.

private UIImage GetVideoThumbnail(string path)
{
    try {
        CMTime actualTime;
        NSError outError;
        using (var asset = AVAsset.FromUrl (NSUrl.FromFilename (path)))
        using (var imageGen = new AVAssetImageGenerator (asset))
        using (var imageRef = imageGen.CopyCGImageAtTime (new CMTime (1, 1), out actualTime, out outError)) {
            return UIImage.FromImage (imageRef);
        }   
    } catch {
        return null;
    }
}

Posts

  • FebinDonzManGroveFebinDonzManGrove USMember ✭✭

    thanks Danny Cabrera,

    it works

  • csampaio01csampaio01 PTMember ✭✭✭

    What plugin did you used?

  • BytesGuyBytesGuy GBXamarin Team Xamurai

    @carlasampaio01 I can't see a plugin being used in the code above, you just need to include CoreMedia and AVFoundation

  • DannyCDannyC US ✭✭✭✭

    Correct, @BytesGuy there's no plugin.

  • csampaio01csampaio01 PTMember ✭✭✭

    I am creating a list with many video thumbnails. But it takes a bit long to load all. I convert the image to an array of bytes. Is that why its taking a bit long?

    `byte[] VideoThumbnail.Generate(string filename)
    {
    try
    {
    CMTime actualTime;
    NSError outError;

                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var filename2 = Path.Combine(documents, filename);
    
                using (var asset = AVAsset.FromUrl(new NSUrl(filename2, false)))
                using (var imageGen = new AVAssetImageGenerator(asset))
                using (var imageRef = imageGen.CopyCGImageAtTime(new CMTime (3,1), out actualTime, out outError))
                {
                    UIImage imagem = UIImage.FromImage(imageRef);
    
                    using (NSData imageData = imagem.AsPNG())
                    {
                        byte[] myByteArray = new Byte[imageData.Length];
                        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
    
                        return myByteArray;
                    }
                }
            }
            catch
            {
                return null;
            }
        }`
    
  • rraallvvrraallvv Member ✭✭

    Does anyone have a snippet for Android?

Sign In or Register to comment.