2012-07-31 114 views
0

我有一个图像宽度/高度/跨度和缓冲区。C#将步幅/缓冲区/宽度/高度转换为位图

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

+0

HTTP://whathaveyoutried.com/...表现出一定的代码... – 2012-07-31 11:41:49

+0

你的意思是说上传时想要以二进制格式将图像保存到数据库中,并检索值并显示为图像? – 2012-07-31 11:42:53

+0

我的意思是有人编写了一个代码来获取摄像机的高度/宽度/跨度/缓冲区。他现在要我做点什么。我想使用位图图像,他使用writeablebitmap并告诉我如何获得步幅/宽度等... – Mattb2291 2012-07-31 12:04:19

回答

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(); 
} 

更新:

Probabl y最好是将图像字节手动复制到新创建的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); 
+0

我所给出的是我可以在参数 中找到步幅/缓冲区等ie - > args .Buffer = buffer ... args.Stride = stride等 但是使用 位图测试=新的位图(args.Width,args.Height,args.Stride,PixelFormats.Rgb24,args.Buffer); 给了我一个错误:(我有点新的图像编程... – Mattb2291 2012-07-31 12:02:09

+0

这个工作......好吧......让我到某个地方......? var test = BitmapFrame.Create(args.Width, args.Height,300D,300D,PixelFormats.Rgb24,null,args.Buffer,args.Stride); – Mattb2291 2012-07-31 12:14:49

+0

'args.Buffer'' byte []'还有'System.Drawing.Bitmap'和'BitmapFrame '来自2个不同的GUI框架,你必须决定使用什么 – max 2012-07-31 12:18:26

0

,如果你有缓冲区的字节[],宽度和高度+的像素格式(跨步)这应该工作

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; 
    } 
相关问题