C#:使用字节数组位图创建 [英] C#: Bitmap Creation using bytes array
问题描述
我想用用以下code字节数组动态地创建位图图像
I am trying to dynamically create a Bitmap Image using byte array using following code
Bitmap GetImage()
{
IntPtr ip = Marshal.AllocCoTaskMem(imagesize);
//some code to fill ip
Image img = new Bitmap(
w,
h,
-stride,
PixelFormat.Format24bppRgb,
(IntPtr)(ip.ToInt32() + imagesize - stride)
);
Marshal.FreeCoTaskMem( ip); // Comment this line to work
return img;
}
void SaveImage()
{
Image img = GetImage();
img.save("test.bmp"); // This call fails
img.Dispose();
}
现在我的问题是,我想返回一个位图,但在同一时间,我不希望保留的IP指针作为分配的内存泄漏。它永远不会被释放。 我怎样才能返回的字节数组,而没有功能的getImage的调用者创建了一个图像(),以释放内存。
Now my problem is I want to return a Bitmap but at the same time I don't want to keep the ip pointer as that memory allocated leaks. It is never freed. How can I return a Image created with bytes array and without bothering the caller of the function GetImage() to free up the memory.
推荐答案
最简单的方法可能是创建位图(虽然在的 我用一个正常的类似code 字节[]
然后固定
块,而不是直接使用 AllocCoTaskMem
),然后创建一个第二的位图
。呼叫 Graphics.FromImage
在第二位图,然后 Graphics.DrawImage
使用的第一的位图以有效地第一个位图的内容复制到第二。然后,您可以调用处置
上的第一个位图,释放内存,并使用第二位图这基本上是一个副本。
The simplest way may be to create the bitmap (although in similar code I've used a normal byte[]
and then a fixed
block, rather than directly using AllocCoTaskMem
), and then create a second Bitmap
of the same size. Call Graphics.FromImage
on the second bitmap, then Graphics.DrawImage
using the first bitmap to effectively copy the contents of the first bitmap onto the second. You can then call Dispose
on the first bitmap, release the memory, and use the second bitmap which is basically a copy.
有可能是一个更有效的方法来做到这一点,如果你更精通形象的东西,但如果你只是在寻找一种方式来获得它的工作,这是一个出发点:)
There may well be a more efficient way to do it if you're more proficient with image stuff, but if you're just looking for a way to get it to work, it's a starting point :)
编辑:zachrrs的评论确实让事情变得更容易使用位图(图片)构造器:
zachrrs's comment does indeed make things easier using the Bitmap(Image) constructor:
using (Bitmap original = new Bitmap(...))
{
Bitmap copy = new Bitmap(originalImage);
// Then return "copy" from your method, and you can free the
// memory
}
这篇关于C#:使用字节数组位图创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!