我们有一个要求,除了客户端验证之外,我们还需要在 MVC Controller 中验证上传图像的透明度。我们知道可以使用 System.Drawing 库来完成此操作,但是由于性能问题,我们将不再使用 System.Drawing,并且我们的目标是将应用程序部署到不支持 GDI 的云中。有没有一种方法可以使用 Imagesharp 验证上传图像的透明度。谢谢。
最佳答案
这是一个有趣的问题,但有些含糊之处。我不知道您是否想检查透明像素的潜力,或者图像中是否确实存在透明像素。每个场景都需要非常不同的行为。
场景 1:测试潜在透明度
为此,您需要查询元数据。
Image
类型及其通用变体包含一个名为 Metadata
的属性。其类型为ImageMetadata
。您可以查询此类型以获取特定于格式的元数据。
例如。如果你想查询 png 元数据,你可以使用
// Get the metadata. Using Identity allows this without fully
// decoding the image pixel data.
using var info = Image.Identify(...);
PngMetadata meta = info.Metadata.GetPngMetadata();
// Query the color type to get color information.
PngColorType = meta.ColorType;
PngColorType
实际上可以支持每个条目的 alpha 组件。
GrayscaleWithAlpha
灰度
*RgbWithAlpha
Rgba
*调色板
*
(*) 仅当 PngMetadata.HasTransparency
为 true 时才透明。
场景 2:测试实际透明度
为此,您需要将图像完全解码为支持透明度的像素格式。
using var image = Image<Rgba32>.Load(...);
for (int y = 0; y < image.Height; y++)
{
// It's faster to get the row and avoid a per-pixel multiplication using
// the image[x, y] indexer
Span<Rgba32> row = image.GetPixelRowSpan(y);
for (int x = 0; x < row.Length; x++)
{
Rgba32 pixel = row[x];
if (pixel.A < byte.MaxValue)
{
// return true.
}
}
}
根据您的场景,这两种方法都应该足够快。
关于asp.net-core-mvc - 有没有办法使用 ImageSharp 验证图像的透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62961179/