asp.net-core-mvc - 有没有办法使用 ImageSharp 验证图像的透明度?

标签 asp.net-core-mvc asp.net-core-3.1 imagesharp

我们有一个要求,除了客户端验证之外,我们还需要在 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/

相关文章:

c# - 升级到 .net core 3.0 后报错“找不到网页地址为 : https://localhost:44374/"的网页

asp.net-core - 具有动态(运行时)值的选项配置

asp.net-core - 如何在 ASP.NET CORE 3.1 中获取客户端 IP 地址?

barcode - 如何在 .Net Core 2.0 中使用 ZXing.Net 和 ImageSharp 创建条码图像

asp.net-core - 绑定(bind)操作参数模型时 ValidationContext.set_DisplayName 中的 ArgumentNullException

c# - 如何在 EF Core 中获取数据库表主键列的列表

c# - 将 Hangfire 作业记录到 Application Insights 并将事件与操作 ID 相关联

c# - 登录 ASP.NET Core 3.1 后如何获取用户信息

c# - 如何使用 ImageSharp 调整中心大小并裁剪图像