c# - 从原始字节创建位图对象

标签 c# bitmapimage

我正在尝试从原始字节创建位图对象,我的 PixelFormatRGB 每个样本 8 位,即每个像素 3 个字节。现在为此,我的步幅将是宽度的 3 倍。

但是 Bitmap 类总是在寻找步长值的 4 倍数。请帮我解决这个问题。如果我给出 4 的乘数,图像就无法正常显示。

Bitmap im = new Bitmap(MyOBJ.PixelData.Columns, MyOBJ.PixelData.Rows, (MyOBJ.PixelData.Columns*3),
System.Drawing.Imaging.PixelFormat.Format24bppRgb, Marshal.UnsafeAddrOfPinnedArrayElement(images[imageIndex], 0));

最佳答案

我写了一个简短的示例,它将填充数组的每一行以使其适应所需的格式。它将创建一个 2x2 棋盘位图。

byte[] bytes =
    {
        255, 255, 255,
        0, 0, 0,
        0, 0, 0,
        255, 255, 255,
    };
var columns = 2;
var rows = 2;
var stride = columns*4;
var newbytes = PadLines(bytes, rows, columns);
var im = new Bitmap(columns, rows, stride,
                    PixelFormat.Format24bppRgb, 
                    Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));

PadLines 方法写在下面。我尝试通过使用 Buffer.BlockCopy 来优化它,以防您的位图很大。

static byte[] PadLines(byte[] bytes, int rows, int columns)
{
    //The old and new offsets could be passed through parameters,
    //but I hardcoded them here as a sample.
    var currentStride = columns*3;
    var newStride = columns*4;
    var newBytes = new byte[newStride*rows];
    for (var i = 0; i < rows; i++)
        Buffer.BlockCopy(bytes, currentStride*i, newBytes, newStride * i, currentStride);
    return newBytes;
}

关于c# - 从原始字节创建位图对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092290/

相关文章:

android - 在另一个 Android 上覆盖位图

javascript - ASP.NET 隐藏字段不发布

c# - 如何解决 C# Premature Object Dispose

c# - 在 C# 中的 Selenium WebDriver 中使用特定的 Firefox 配置文件

c# - 使用 Rosyln 将 switch block 重写为 if/else

Android处理图像处理时的内存不足异常

c# - 将字符串设置到某个位置

c++ - 如何将子窗口的客户区保存到位图文件中?

ios - 从黑白位图图像中提取路径信息

c# - 如何将 WriteableBitmap 转换为 BitmapImage?