C#将stride / buffer / width / height转换为位图

时间:2012-07-31 11:40:25

标签: c# bitmap writeablebitmap

我有一个图像宽度/高度/步幅和缓冲区。

如何将此信息转换为System.Drawing.Bitmap?如果我有这4件事,我可以取回原始图像吗?

2 个答案:

答案 0 :(得分:1)

有一个Bitmap构造函数重载,需要你拥有的所有内容(加上PixelFormat):

public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);

这可能有效(如果args.Buffer是一个blittable类型的数组,例如byte):

Bitmap bitmap;
var gch = System.Runtime.InteropServices.GCHandle.Alloc(args.Buffer, GCHandleType.Pinned);
try
{
    bitmap = new Bitmap(
        args.Width, args.Height, args.Stride,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb,
        gch.AddrOfPinnedObject());
}
finally
{
    gch.Free();
}

更新

可能最好手动将图像字节复制到新创建的Bitmap,因为看起来构造函数不会这样做,并且如果byte[]图像数据数组被垃圾收集各种各样的坏事情可能发生。

var bitmap = new Bitmap(args.Width, args.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var data = bitmap.LockBits(
    new Rectangle(0, 0, args.Width, args.Height),
    System.Drawing.Imaging.ImageLockMode.WriteOnly,
    System.Drawing.Imaging.PixelFormat.Format24bppRgb);

if(data.Stride == args.Stride)
{
    Marshal.Copy(args.Buffer, 0, data.Scan0, args.Stride * args.Height);
}
else
{
    int arrayOffset = 0;
    int imageOffset = 0;
    for(int y = 0; y < args.Height; ++y)
    {
        Marshal.Copy(args.Buffer, arrayOffset, (IntPtr)(((long)data.Scan0) + imageOffset), data.Stride);
        arrayOffset += args.Stride;
        imageOffset += data.Stride;
    }
}

bitmap.UnlockBits(data);

答案 1 :(得分:0)

如果缓冲区为byte [],宽度和高度+ pixelformat(stride)

,这应该可以工作
    public Bitmap CreateBitmapFromRawDataBuffer(int width, int height, PixelFormat imagePixelFormat, byte[] buffer)
    {
        Size imageSize = new Size(width, height);

        Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);
        Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

        // Lock all bitmap's pixels.
        BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);

        // Copy the buffer into bitmapData.
        System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);

        // Unlock  all bitmap's pixels.
        bitmap.UnlockBits(bitmapData);

        return bitmap;
    }