在 Java SWT 中使用 ImageData 在 Canvas 上显示图像的 WPF 等效项是什么

What is the WPF equivalent of displaying an Image on a Canvas using ImageData in Java SWT

以下 Java SWT 代码的 WPF 等价物是什么?我想从 RGBA 值列表创建一个图像并显示在 Canvas.

private Image GetImage()
{

    ImageData imageData = new ImageData(imageWidth, imageHeight,32,palette);

    int pixelVecLoc=0;
    for (int h = 0; h<imageHeight && (pixelVecLoc < currentImagePixelVec.size()); h++)
    {
        for (int w = 0; w<imageWidth && (pixelVecLoc < currentImagePixelVec.size()); w++)
        {
            int p = 0;
            Pixel pixel = currentImagePixelVec.get(pixelVecLoc);
            p = (pixel.Alpha<<24) | (pixel.Red<<16) | (pixel.Green<<8) | pixel.Blue;                
            imageData.setPixel(w, h, p);            
            pixelVecLoc++;
        }
    }

    imageData = imageData.scaledTo(imageScaleWidth, imageScaleHeight);
    Image image = ImageDescriptor.createFromImageData(imageData).createImage();
    return image;   
}

然后画在Canvas:

gc.drawImage(image, 0, 0); 

这是一个简短的片段,展示了如何创建自定义 RGBA 缓冲区并将像素数据写入其中 (based on this example):

int width = 512;
int height = 256;
int stride = width * 4 + (width % 4);
int pixelWidth = 4;  // RGBA (BGRA)
byte[] imageData = new byte[width * stride];       // raw byte buffer

for (int y = 0; y < height; y++)
{
    int yPos = y * stride;

    for (int x = 0; x < width; x++)
    {
        int xPos = yPos + x * pixelWidth;

        imageData[xPos + 2] = (byte) (RedValue);   // replace *Value with source data
        imageData[xPos + 1] = (byte) (GreenValue);
        imageData[xPos    ] = (byte) (BlueValue);
        imageData[xPos + 3] = (byte) (AlphaValue);
    }
}

然后使用BitmapSource.Create Method (Int32, Int32, Double, Double, PixelFormat, BitmapPalette, IntPtr, Int32, Int32) method together with a PixelFormats:

BitmapSource bmp = 
  BitmapSource.Create(
    width, 
    height, 
    96,                    // Horizontal DPI
    96,                    // Vertical DPI
    PixelFormats.Bgra32,   // 32-bit BGRA
    null,                  // no palette
    imageData,             // byte buffer
    imageData.Length,      // buffer size
    stride);               // stride

请注意,除代码段中所示的 alpha 组件 (BGRA) 外,字节顺序是相反的。

要将结果传输到 canvas,您可以先创建一个 Image,将 BitmapSource 设置为 Source,最后将其添加到canvas:

// create image and set image as source
Image BmpImg = New Image();
BmpImg.Width = width;
BmpImg.Height = height;
BmpImg.Source = bmp;

// add image to canvas
canvas.Children.Add(BmpImg);

Canvas.SetLeft(BmpImg, 0);  // to set position (x,y)
Canvas.SetTop(BmpImg, 0);