Forum Xamarin Xamarin.iOS

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?

  • YadavVinodYadavVinod USMember ✭✭
    edited April 10

    private async Task GetThumbAsync(Bitmap bitmap)
    {
    MemoryStream stream = new MemoryStream();
    bitmap.Compress(Bitmap.CompressFormat.Png,0,stream);
    byte[] bitmapData = stream.ToArray();
    var a = ImageSource.FromStream(() => new MemoryStream(bitmapData));
    var image = bitmap;
    var absolutePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
    var folderPath = $"{absolutePath}/Camera";
    var filePath = System.IO.Path.Combine(folderPath,string.Format("photo_{0}.jpg",Guid.NewGuid()));
    var fileStream = new FileStream(filePath,FileMode.Create);

            await image.CompressAsync(Bitmap.CompressFormat.Jpeg,50,fileStream);
            fileStream.Close();
            image.Recycle();
    
            var intent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile);
            var file = new Java.IO.File(filePath);
            var uri = Android.Net.Uri.FromFile(file);
            intent.SetData(uri);
            MainActivity.Instance.SendBroadcast(intent);
            return filePath;
        }
    
        public Task<string> GenerateThumbImageForPhotoAsync(string bitmap)
        {
            if(bitmap!=null)
            {
                Bitmap bm = BitmapFactory.DecodeFile(bitmap);
    
                var s = GetThumbAsync(bm);
                return  s;
            }
            return null;
        }
    
Sign In or Register to comment.