代码之家  ›  专栏  ›  技术社区  ›  Matt Ellen Bipin Vayalu

字节[]到灰度位图图像

  •  2
  • Matt Ellen Bipin Vayalu  · 技术社区  · 16 年前

    然后我将这个字节数组转换成一个内存流( dataStream BitmapImage 像这样:

    imgScan.Width = 128;
    imgScan.Height = 128;
    BitmapImage bi = new BitmapImage();
    bi.SourceRect = new Int32Rect(0, 0, width, height);
    bi.StreamSource = dataStream;
    imgScan.Source = bi;
    

    在这里 imgScan 是一个 System.Windows.Controls.Image

    我该怎么办?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Will Dean    16 年前

    我想您会发现在您的代码中,流应该包含一个完整的图像文件,而不是一个原始数据块。下面是从一块数据中生成位图(虽然不是灰度图,但您可能会明白这一点):

    const int bytesPerPixel = 4;
    int stride = bytesPerPixel * pixelsPerLine;
    UInt32[] pixelBytes = new uint[lineCount * pixelsPerLine];
    
    for (int y = 0; y < lineCount; y++)
    {
        int destinationLineStart = y * pixelsPerLine;
        int sourceLineStart = y * pixelsPerLine;
        for (int x = 0; x < pixelsPerLine; x++)
        {
            pixelBytes[x] = _rgbPixels[x].Pbgr32;
        }
    }
    var bmp = BitmapSource.Create(pixelsPerLine, lineCount, 96, 96, PixelFormats.Pbgra32, null, pixelBytes, stride);
    bmp.Freeze();
    return bmp;
    

    您已经在嵌套循环中完成了位(生成字节数组),但我将其保留在中,以便您可以看到在创建之前发生了什么