如何从Softwarebitmap设置/获取像素 [英] How to set/get pixel from Softwarebitmap
问题描述
我正在尝试从 Softwarebitmap
更改像素.
I am trying to change pixels from a Softwarebitmap
.
我想知道Softwarebitmap UWP中是否有 Bitmap.Get/SetPixel(x,y,color)
的等效项.
I want to know if there is an equivalent for Bitmap.Get/SetPixel(x,y,color)
in Softwarebitmap UWP.
推荐答案
如果要读写软件位图,则应使用不安全的代码.
If you want to read and write softwareBitmap that you should use unsafe code.
要使用softwareBitmap,很难编写一些代码.
To use softwareBitmap is hard that you should write some code.
首先使用一些代码.
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);
}
您可以使用此代码更改像素.
You can use this code to change the pixel.
创建软位图.
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
}
}
}
}
}
您可以写入用于写入dataInBytes的像素,而应该使用字节.
You can write the pixel for write the dataInBytes and you should use byte.
因为像素是BGRA,您应该写入此字节.
For the pixel is BGRA and you should write this byte.
如果要显示它,则需要在BitmapPixelFormat不是Bgra8并且BitmapAlphaMode是Straight时进行转换,并且可以使用此代码.
If you want to show it, you need to Convert when the BitmapPixelFormat isnt Bgra8 and the BitmapAlphaMode is Straight and you can use this code.
if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
{
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}
此代码可以将其显示在图像上.
This code can show it to Image.
var source = new SoftwareBitmapSource();
await source.SetBitmapAsync(softwareBitmap);
Image.Source = source;
这篇关于如何从Softwarebitmap设置/获取像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!