C# 如何将图像从位图放入图片框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/743549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put image in a picture box from Bitmap
提问by Ivan Prodanov
Is it possible to load a picture from memory (byte[]
or stream
or Bitmap
) without saving it to disk?
是否可以从内存(byte[]
或stream
或Bitmap
)加载图片而不将其保存到磁盘?
This is the code I use to turn the byte[]
array into a Bitmap
:
这是我用来将byte[]
数组转换为 a的代码Bitmap
:
unsafe
{
fixed (byte* ptr = Misc.ConvertFromUInt32Array(image))
{
Bitmap bmp = new Bitmap(200, 64, 800, PixelFormat.Format32bppRgb, new IntPtr(ptr));
bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
bmp.MakeTransparent(Color.Black);
bmp.Save("test.bmp");
}
}
Instead of using Bmp.save()
, can I put the Bitmap
in the picture box on my form?
除了使用Bmp.save()
,我可以将 放在Bitmap
表单的图片框中吗?
采纳答案by ChrisF
Have you tried this?
你试过这个吗?
pictureBox.Image = bmp;
回答by r.mirzojonov
If you are working with C++ programming language, it can be done like this:
如果您正在使用 C++ 编程语言,则可以这样做:
void backGroundImage()
{
Image^ back = gcnew Bitmap("C:\Users\User\Documents\image.bmp");
pictureBox1->BackGroundImage = back;
};
Then you can call backGroundImage
when you need to load a bitmap.
然后就可以backGroundImage
在需要加载位图的时候调用了。
回答by JSideris
I had some code resembling the accepted answer that caused a memory leak. Problem is that when you set the picture box image to the bitmap, you're still referring to the bitmap, rather than creating a copy. If you need to set the image multiple times you need to make sure you're disposing all the old bitmaps.
我有一些类似于导致内存泄漏的公认答案的代码。问题是当您将图片框图像设置为位图时,您仍然引用位图,而不是创建副本。如果您需要多次设置图像,则需要确保处理所有旧位图。
This is for anyone who's looking to clonea bitmap to an image box. Try this:
这是任何人谁是寻找克隆一个位图图像框。尝试这个:
if (pictureBox.Image != null) pictureBox.Image.Dispose();
pictureBox.Image = myBitmap.Clone(
new Rectangle(0, 0, myBitmap.Width, myBitmap.Height),
System.Drawing.Imaging.PixelFormat.DontCare);