简体   繁体   English

如何使用 C# Dot Net Core 压缩图像大小

[英]How to compress the image size using C# Dot Net Core

I am using .NET Core 2.2 In my code, I am using IFormFile to upload images.我使用 .NET Core 2.2 在我的代码中,我使用IFormFile上传图像。 How can I compress the image size (to KB) just before it is uploaded to the server ?如何在将图像上传到服务器之前将其压缩(以 KB 为单位)? I search for solutions but those answers were related to Bitmap but since I am using IFormFile therefore I want solution related to it.我搜索解决方案,但这些答案与位图有关,但由于我使用的是 IFormFile,因此我想要与之相关的解决方案。

I will internally check the image size and if its size is upto 700KB, I don't want to compress.我会在内部检查图像大小,如果它的大小高达 700KB,我不想压缩。 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.我尝试使用 Magick.NET 包。 But the problem is, how can I make IFormFile to MagickImage type ?但问题是,如何将 IFormFile 设为 MagickImage 类型?

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);
   }
}

I have used Magick.NET library which is available for both .NET and .NET Core to compress images.我使用了可用于 .NET 和 .NET Core 的Magick.NET库来压缩图像。 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[]在您的情况下,您需要将图像临时保存在某处并使用路径(类似于我的示例),或者将其转换为内存中an array of byte并读取它,因为它接受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");                 
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM