当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to display a PNG from a file?

问题描述:

I want to switch the image that is displayed on a toolStripButton. But I juste can't find how to do that.

I think it should be something like:

btSearch.Image = new Image("myimage.png");

But it doesn't work ( new Image seems not to exist).

Thank you for your help

网友答案:

I recommend the Image.FromStream() method as it doesn't lock the actual file.

For example:

using (var stream = File.OpenRead(path))
using (var image = Image.FromStream(stream))
{
    //Black magic here.
}

Note that you must keep the stream open for the lifetime of the Image. The stream is reset to zero if this method is called successively with the same stream.

Here's a previous discussion with an answer from Jon Skeet.

网友答案:

Use Image.FromFile():

btSearch.Image = Image.FromFile("myimage.png");

Unfortunately, the file will be locked until you dispose the image. For another solution, see the question, ToolStripButton: what's wrong with assigning an image programmatically.

分享给朋友:
您可能感兴趣的文章:
随机阅读: