如何使用 .NET Core 压缩图像大小?

How to compress the image size using .NET Core?

我正在使用 .NET Core 2.2。在我的代码中,我使用 IFormFile 上传图片。如何在将图像上传到服务器之前压缩图像大小(至 KB)?我搜索解决方案,但这些答案与 Bitmap 有关,但由于我使用的是 IFormFile,因此我想要与之相关的解决方案。

我会在内部检查图像大小,如果它的大小达到 700KB,我不想压缩。但如果它更高,那么我想压缩并上传。示例代码将非常有用

我尝试使用 Magick.NET 包。如何将 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);
   }
}

我使用了 Magick.NET 库,它可用于 .NET 和 .NET Core 来压缩图像。有关详细信息,请参阅其文档。

在您的情况下,您需要将图像临时保存在某处并使用路径(类似于我的示例),或者将其转换为内存中的 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");                 
        }