我有本质上是一个二维颜色数组,每个索引代表像素,值是该像素的颜色。为简单起见,让我们想象一个 3x3 像素阵列,它基本上具有 1 像素行红色、1 像素行绿色和 1 像素行蓝色:
Color[,] colorArray = new Color[3,3];
for (int i = 0; i < 3; ++i)
{
colorArray[0,i] = Colors.Red;
colorArray[1,i] = Colors.Green;
colorArray[2,i] = Colors.Blue;
}
我有一个带有图像的 XAML 文件(同样,为简单起见,我们假设图像也是 3x3 像素)。如何将上述像素数据写入可以在该图像文件中显示的内容?
编辑:
我已经尝试使用两者WriteableBitmaps
,BitmapSources
但似乎无法让它们工作。例如,下面的代码(我只是想把整个屏幕涂成黄色)会产生一个白色的图像(从这里借来的)。
位图源示例
uint[] pixelData = new uint[width * height];
for (int y = 0; y < height; ++y)
{
int yIndex = y * width;
for (int x = 0; x < width; ++x)
{
pixelData[x + yIndex] = (0 << 24) + (255 << 16) + (255 << 8) + 255;
}
}
var bmp = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, width * 4);
TestImage.Source = bmp;
可写位图示例
WriteableBitmap wb = new WriteableBitmap(width, height, dpi, dpi, pf, null);
byte[] pixelData = new byte[height * width * 4];
for (int i = 0; i < (int)wb.Height; i++)
{
for (int j = 0; j < (int)wb.Width; j++)
{
var color = colors[i, j];
var idx = j * 4 + i * width * 4;
byte blue = color.B;
byte green = color.G;
byte red = color.R;
pixelData[idx] = blue;
pixelData[idx + 1] = green;
pixelData[idx + 2] = red;
pixelData[idx + 3] = 255;
//byte[] colorData = { blue, green, red, 255 };
//Int32Rect rect = new Int32Rect(j, i, 1, 1);
//wb.WritePixels(rect, colorData, 4, 0);
}
}
Int32Rect rect = new Int32Rect(0, 0, width, height);
wb.WritePixels(rect, pixelData, 4, 0);
TestImage.Source = wb;