Reputation: 301
I am using .NET Core 2.2. In my code, I am using IFormFile to upload images. How can I compress the image size (to KB) just before it is uploaded to the server ? I search for solutions but those answers were related to Bitmap but since I am using IFormFile therefore I want solution related to it.
I will internally check the image size and if its size is up to 700KB, I don't want to compress. But if it is higher, then I want to compress and upload. Sample codes would be very useful
I tried to use Magick.NET package. How can I make IFormFile to MagickImage type?
foreach(IFormFile photo in Images)
{
using (MagickImage mi = photo) // Cannot implicitly convert type
//Microsoft.AspNetCore.Http.IFormFile to ImageMagick.MagickImage
{
mi.Format = Image.Jpeg;
mi.Resize(40, 40);
mi.Quality = 10;
mi.Write(imageFile);
}
}
Upvotes: 6
Views: 22215
Reputation: 3826
I have used Magick.NET library which is available for both .NET and .NET Core to compress images. Refer to its documentation for more details.
In your case you either need to save the image temporarily somewhere and use the path (similar to my example), or convert it to an array of byte
in memory and read that since it accept Byte[]
using (MagickImage image = new MagickImage(@"YourImage.jpg"))
{
image.Format = image.Format; // Get or Set the format of the image.
image.Resize(40, 40); // fit the image into the requested width and height.
image.Quality = 10; // This is the Compression level.
image.Write("YourFinalImage.jpg");
}
Upvotes: 22