如何使用 SkiaSharp 找到解码位图的 PixelFormat

Par*_*thi 5 2d skia asp.net-core skiasharp

在 System.Drawing 中,我们从 Image 对象中检索 PixelFormat,但 SkiaSharp.SkImage 不提供 API 来查找解码图像的 PixelFormat。是否有任何其他解决方法来查找解码图像的 PixelFormat 以及我们如何创建具有 PixelFormat 值的 Image 作为 System.Drawing.Image

Mat*_*hew 6

简短回答

有这个方面,但是又分为两种:SKColorTypeSKAlphaType。这些属性可以在类型上找到SKImageInfo

SKImageSKBitmap

在分享真正的答案之前,先简要介绍一下这两种图像类型之间的差异。

SKBitmap (仅限光栅)

ASKBitmap纯光栅图形,这意味着颜色和 alpha 类型信息很容易获得。这是在Info属性中。

SKBitmap bitmap = ...;
SKColorType colorType = bitmap.Info.ColorType;
SKAlphaType alphaType = bitmap.Info.AlphaType;
Run Code Online (Sandbox Code Playgroud)

SKImage (光栅或纹理)

SKImage有点不同,因为它实际上可能不是光栅位图。AnSKImage可以是 GPU 对象,例如 OpenGL 纹理。因此,此颜色类型不适用。因此,在您使用光栅位图的情况下,请使用SKBitmap而不是SKImage.

然而,仍然有希望SKImage,因为基于光栅的SKImage实际上SKBitmap在幕后使用了 。如果您知道您的SKImage图像是光栅图像,那么您可以使用该PeekPixels()方法来获取SKPixmap也具有Info属性的对象。SKPixmap是一种精简类型,包含对图像数据、信息和一些其他属性的引用。

要检查某个图像SKImage是纹理图像还是光栅图像,可以使用该IsTextureBacked属性。

SKImage image = ...;
if (!image.IsTextureBacked) {
    using (SKPixmap pixmap = image.PeekPixels()) {
        SKColorType colorType = pixmap.ColorType;
        SKAlphaType alphaType = pixmap.AlphaType;
    }
} else {
    // this is a texture on the GPU and can't be determined easily
}
Run Code Online (Sandbox Code Playgroud)

更长的答案

所以现在更长的答案...SKColorTypeSKAlphaType类型一起形成相当于PixelFormat.

例如:

Rgba8888和之间的主要区别Bgra8888在于应用程序运行的平台。通常,您会根据 来检查颜色类型,SKImageInfo.PlatformColorType因为这样就会知道本机颜色类型应该是什么。