ImageFactory 正在生成.webp大于.jpeg文件的文件



我有一个基于 ASP.NET Core的WebAPI。我正在尝试将上传的.jpeg图像转换为.webp。我尝试使用ImageProcessor库和ImageProcessor.Plugins.WebP来生成.webp压缩文件。这是我使用的代码

public async Task<IActionResult> Store(IFormFile file)
{
if(!ModelState.IsValid) 
{
return Problem("Invalid model!");
}
string absoluteFilename = Path.Combine("d:/uploaded_images", Path.GetRandomFileName() + ".webp");
using var stream = new FileStream(absoluteFilename, FileMode.Create);
using ImageFactory imageFactory = new ImageFactory(preserveExifData: false);
imageFactory.Load(file.OpenReadStream())
.Format(new WebPFormat())
.Quality(100)
.Save(stream);
return Ok(absoluteFilename);
}

但是上面的代码需要一个 83.9KB 的 JPEG 文件并创建了一个 379KB 的 WEBP 文件。我尝试使用在线转换器将我的 JPEG 文件转换为 WEBP,结果是 73KB。

如何将.jpeg文件正确转换为.webp

ImageProcessorImageProcessor.Plugins.WebP不适用于动画 gif,请摆脱它并改用 ImageMagick.NET。

public async Task<IActionResult> Store(IFormFile file)
{
if (!ModelState.IsValid)
{
return Problem("Invalid model!");
}
string absoluteFilename = Path.Combine("d:/uploaded_images", Path.GetRandomFileName() + ".webp");
using FileStream stream = new FileStream(absoluteFilename, FileMode.Create);
using MagickImageCollection images = new MagickImageCollection(stream);
foreach (IMagickImage<ushort> image in images)
{
image.Quality = 100;
image.Settings.SetDefines(new WebPWriteDefines() { Lossless = true, Method = 6 });
image.Settings.Compression = CompressionMethod.WebP;
image.Format = MagickFormat.WebP;
}
images.Write(absoluteFilename, MagickFormat.WebP);
return Ok(absoluteFilename);
}

根据需要调整此代码段。

我检查了这个包的源代码,我认为在将源图像转换为Bitmap的过程中会丢失很多压缩优势。我尝试使用Google的工具将文件转换为webp,它将图像文件从100 KB减少到74 KB。 您可以将其嵌入到项目中。

在 Web 环境中启动 exe 可能很棘手,但您可以查看有关此主题的一些文章 http://www.codedigest.com/articles/aspnet/334_working_with_exe_in_aspnet-calling_killingaborting_an_exe.aspx

有关cwebp的更多信息,请点击此处 https://developers.google.com/speed/webp/docs/cwebp

下载链接 https://developers.google.com/speed/webp/download

using System;
using System.Diagnostics;
namespace ConsoleApp15
{
class Program
{
static void Main(string[] args)
{
var filePath = @"C:UsersjjjjjjjjjjjjDownloadslibwebp-1.0.3-windows-x86bincwebp.exe";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = filePath;
startInfo.Arguments = "file.jpeg -o file.webp";
startInfo.CreateNoWindow = true; // I've read some articles this is required for launching exe in Web environment
startInfo.UseShellExecute = false;
try
{
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}

最新更新