如何使用 .NET Core 将 JPEG 转换为 WebP 格式?



我有一个 ASP.NET Core 3.1 WebAPI,负责为我拥有的其他应用程序提供图像。我正在尝试提高应用程序的性能。我从运行PageSpeed Insights测试中得到的反馈之一是以下一代格式提供图像。

我的 WebAPI 服务器的所有图像都是 JPEG 格式。我对图像压缩或图像格式了解不多,但我想评估将 JPEG 图像转换为 WebP 的结果,因为研究表明 WebP 会带来更好的结果。

我使用以下ImageProcessor类将上传的图像保存到我的 WebAPI。

public class ImageProcessor
{
public Image GetResizedImage(Stream stream, int newWidth, out ImageFormat imageFormat)
{
Image sourceImage = Image.FromStream(stream);
SizeF thumbSize = GetNewSize(sourceImage, newWidth);
imageFormat = sourceImage.RawFormat;
return ResizeImage(sourceImage, (int)thumbSize.Width, (int)thumbSize.Height);
}
protected SizeF GetNewSize(Image img, int newMaxWidth)
{
var size = new SizeF
{
Width = newMaxWidth,
Height = (newMaxWidth * img.Height) / img.Width
};
return size;
}
protected Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
var xRes = Math.Max(Math.Min(image.HorizontalResolution, 96), 72);
var yRes = Math.Max(Math.Min(image.VerticalResolution, 96), 72);
destImage.SetResolution(xRes, yRes);
using (Graphics graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (ImageAttributes wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
}

以下是我调用ImageProcessor类以从控制器将图像存储在磁盘上的方法

public async Task<IActionResult> Store(IFormFile file)
{
if(!ModelState.IsValid) 
{
return Problem("Invalid model!");
}
// Process Image
Image image = GetResizedImage(file.OpenReadStream(), 1024, out ImageFormat imageFormat);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, imageFormat);
memoryStream.Seek(0, SeekOrigin.Begin);
// Store it on disk
string fullPath = "full path to the new image";
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
using FileStream cacheWriter = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 4096, true);
await memoryStream.CopyToAsync(cacheWriter);
return Ok();
}

问题

如何使用 .Net Core 以 WebP 格式存储图像?

如果我是你,我会考虑安装Thumbor的实例或使用Cloudinary来生成你的webp文件。

然后,您可以使用JS有条件地加载正确的文件。

最新更新