如何将 Xamarin ImageSource 转换为像素操作格式(例如 SkiaSharp 或 GDI)?

问题描述 投票:0回答:1

我正在开发一个 Xamarin.Forms 项目,我需要对通过 Xamarin 的 ImageSource 加载的图像执行像素级操作。我正在寻找一种将 ImageSource 转换为允许我设置和获取单个像素以执行绘图和像素操作等任务的格式的方法。

我尝试过使用 SkiaSharp,并且在将 ImageSource 转换为 SKBitmap 时遇到了问题。这是我的代码片段:

// Example using SkiaSharp
ImageSource imageSource = // my ImageSource;
SKBitmap skBitmap = SKBitmap.Decode(imageSource.ToStream());

但是,我面临着挑战,并且我愿意探索可以实现相同目标的替代库或方法。我的目标是灵活地设置和获取单个像素值以进行图像处理。

此外,如果有一种方法可以在 Xamarin 上下文中使用 GDI 来实现此目的,我也有兴趣探索该途径。

我很欣赏有关如何有效地将 ImageSource 转换为适合像素操作的格式的任何指导或示例,以及是否有我可能考虑的替代库或方法。

谢谢!

c# xamarin gdi skiasharp
1个回答
0
投票

对于 Xamarin.Forms 中图像的像素级操作,SkiaSharp 确实是一个不错的选择。为了处理

ImageSource
,我们必须将其转换为 SkiaSharp 可以解码为
SKBitmap
的流或格式。
ImageSource
类没有内置方法可以直接将其转换为流或
SKBitmap
,但我们可以使用不同类型的
ImageSource
(如
UriImageSource
FileImageSource
等)获取底层图像数据。

下面是将

StreamImageSource
转换为
SKBitmap
的示例:

// Assuming your ImageSource is a StreamImageSource
var imageSource = // your StreamImageSource;

// Get the stream of the image source
StreamImageSource streamImageSource = (StreamImageSource)imageSource;
using (Stream stream = await streamImageSource.Stream(System.Threading.CancellationToken.None))
{
    // Decode the stream to SKBitmap using SkiaSharp
    SKBitmap skBitmap = SKBitmap.Decode(stream);

    // Now you can manipulate pixels with the SKBitmap
}

如果你有

FileImageSource
,你可以直接将文件读入
SKBitmap

// Assuming your ImageSource is a FileImageSource
var imageSource = // your FileImageSource
FileImageSource fileImageSource = (FileImageSource)imageSource;
string filePath = fileImageSource.File;

// Decode the file to SKBitmap using SkiaSharp
SKBitmap skBitmap = SKBitmap.Decode(filePath);

// Now you can manipulate pixels with the SKBitmap

对于

UriImageSource
,您首先将图像数据下载到
Stream
中,然后将
Stream
解码为
SKBitmap

// Assuming your ImageSource is a UriImageSource
var imageSource = // your UriImageSource
UriImageSource uriImageSource = (UriImageSource)imageSource;

using (HttpClient client = new HttpClient())
using (Stream stream = await client.GetStreamAsync(uriImageSource.Uri))
{
    // Decode the stream to SKBitmap using SkiaSharp
    SKBitmap skBitmap = SKBitmap.Decode(stream);

    // Now you can manipulate pixels with the SKBitmap
}

关于 GDI,需要注意的是,GDI+ 不能在 Xamarin.Forms 中直接访问,因为它是一个基于 .NET System.Drawing 的库,适合 Windows 窗体,而不适合跨平台代码。由于 Xamarin.Forms 是跨平台的,因此它依赖于每个平台上的不同图形 API(例如 iOS 上的 Core Graphics 和 Android 上的 Canvas)。因此,使用 SkiaSharp 是首选方法,因为它是跨平台的,并且具有广泛的图形和图像处理功能。

对于实际的像素操作,一旦有了

SKBitmap
,您就可以访问
Pixels
属性:

// Access pixel at (x, y)
SKColor color = skBitmap.GetPixel(x, y);

// Modify pixel at (x, y)
skBitmap.SetPixel(x, y, new SKColor(r, g, b, a)); // where r, g, b, a are byte values of red, green, blue, and alpha channels

请记住处理异常和边缘情况,其中

ImageSource
可能不包含有效的图像数据或图像无法解码。根据获取图像的位置和方式,您可能还需要处理权限、网络故障或不正确的文件路径等问题。

© www.soinside.com 2019 - 2024. All rights reserved.