Search code examples
.netimage.net-coreasp.net-core-3.1webp

Get thumbnail from webp image .net core 3.1


I have an uploade controller that can save image to file and get thumbnail image from the file uploaded. it's working with .jpeg or .png but how can i get thumbnail image from webp extension and save it as .webp too. i got error parameter is not valid

uploadImage(IFormFile file){
....
Stream filestream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(filestream);
var myBitmap = Image.FromStream(filestream);  <----- error: parameter is not valid 

using (var myThumbnail = myBitmap.GetThumbnailImage(150, 150, () => false, IntPtr.Zero))
{
   //e.Graphics.DrawImage(myThumbnail, 150, 75);   // scale main image if thum is big 
   size like 300 * 300
   myThumbnail.Save(thumbFullPathName);
}
filestream.Close();
....
}

Solution

  • Install ImageProcessor nuget package:

    Install-Package System.Drawing.Common
    Install-Package ImageProcessor
    Install-Package ImageProcessor.Plugins.WebP
    

    and save method:

    private void SaveAsThumbnail(IFormFile file, string path, string unicFileName)
        {
            string thumbFolder = Path.Combine(Directory.GetCurrentDirectory(), rootDir, "thumb", path);
            Directory.CreateDirectory(thumbFolder);
            string thumbFullPathName = Path.Combine(thumbFolder, unicFileName);
            using (var webPFileStream = new FileStream(thumbFullPathName, FileMode.Create))
            {
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    imageFactory.Load(file.OpenReadStream());
                    var thumb = imageFactory.Image.GetThumbnailImage(150, 150, () => false, IntPtr.Zero);
                    imageFactory.Format(new WebPFormat())
                                .Quality(90)
                                .Save(webPFileStream);
                }
                webPFileStream.Close();
            }
        }
    

    and ofcurse you can resize it by resize method:

    ImageFactory.Resize...
    

    I found solution from elmah.io web site:

    working with webp in .net core


    also there is another neget package:

    ImageProcessor.NetCore
    ImageProcessorWebP.NetCore