How to display a PNG from a file?
I want to switch the image that is displayed on a toolStripButton开发者_StackOverflow. 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
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.
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.
精彩评论