Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

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();
....
}
question from:https://stackoverflow.com/questions/66066474/get-thumbnail-from-webp-image-net-core-3-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...