Best way to Compress Image in Asp net core

osyris 236 Reputation points
2022-06-10T20:46:46.123+00:00

I want to Compress all uploaded image before it gets Uploaded on the websites disk.
I have allot of small thumbnail sized images (shopping page) on a page so the images need to be at there minimal size while stil be in good quality so it will not take that long to load a page

How I upload the images right now:

                        string name = Guid.NewGuid().ToString() + "_" + image.FileName;  
                        string filepath = Path.Combine(root, name);  
  
                        using var stream = System.IO.File.Create(filepath);  
                        await image.CopyToAsync(stream);  

 
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,207 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jaliya Udagedara 2,736 Reputation points MVP
    2022-06-10T20:59:47.057+00:00

    You can do something like the below,

    Bitmap resizedImage = new(image, new Size(256, 256));  
    using var stream = new MemoryStream();  
    resizedImage.Save(stream, ImageFormat.Jpeg);  
    byte[] bytes = stream.ToArray();  
    
    // Write bytes to your desired location  
    
    0 comments No comments