我正在尝试从Softwarebitmap
更改像素。
我想知道软件位图 UWP 中是否有等效的Bitmap.Get/SetPixel(x,y,color)
。
如果你想读写软件位图,你应该使用不安全的代码。
要使用软件位图很难,你应该写一些代码。
首先使用一些代码。
using System.Runtime.InteropServices;
然后创建一个接口
[ComImport]
[Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
unsafe interface IMemoryBufferByteAccess
{
void GetBuffer(out byte* buffer, out uint capacity);
}
您可以使用此代码更改像素。
创建软位图。
var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, 100, 100, BitmapAlphaMode.Straight);
书写像素。
using (var buffer = softwareBitmap.LockBuffer(BitmapBufferAccessMode.ReadWrite))
{
using (var reference = buffer.CreateReference())
{
unsafe
{
((IMemoryBufferByteAccess) reference).GetBuffer(out var dataInBytes, out _);
// Fill-in the BGRA plane
BitmapPlaneDescription bufferLayout = buffer.GetPlaneDescription(0);
for (int i = 0; i < bufferLayout.Height; i++)
{
for (int j = 0; j < bufferLayout.Width; j++)
{
byte value = (byte) ((float) j / bufferLayout.Width * 255);
dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 0] = value; // B
dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 1] = value; // G
dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 2] = value; // R
dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 3] = (byte) 255; // A
}
}
}
}
}
您可以写入用于写入数据InBytes的像素,并且应该使用字节。
因为像素是BGRA,你应该写这个字节。
如果要显示它,则需要在BitmapPixelFormat不是Bgra8且BitmapAlphaMode为Straight时进行转换,您可以使用此代码。
if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
{
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}
此代码可以将其显示给图像。
var source = new SoftwareBitmapSource();
await source.SetBitmapAsync(softwareBitmap);
Image.Source = source;
请参阅:创建、编辑和保存位图图像 - UWP 应用开发人员