How do I change a PictureBox's image?
Asked Answered
K

3

24

I have a program in C# with a PictureBox object inside a Form. How do I change its picture? The pictures to chose from are in bin/Pics; they are jpeg in format, if that matters..

Kepler answered 14/7, 2012 at 22:35 Comment(0)
T
44

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

Thenceforth answered 14/7, 2012 at 22:39 Comment(3)
Of course, it depends on what you are going to do with the images. I prefer loading images from a Stream because the FromFile() method keeps the file handle open until the end of the applicaition life time. This can lead to unwanted side effects when you try to overwrite the image with a file that has the same name, for example.Dillard
Just to add to the above, I couldn't get my images to display then remembered that you need to add double \\ s for example;pictureBox1.Image = Image.FromFile("C:\\Users\\bob\\Documents\\music.jpg");Janes
@Janes If you decide to use backslashes instead of forward ones, sure. Forward slashes are valid path separators in Windows, so "C:/Users/bob/documents/music.jpg" will work in Windows too. If you're stuck on using backslashes then use a string literal to ignore the unintentional escape characters. i.e. @"C:\Users\bob\Documents\music.jpg"Lockman
S
4

If you have an image imported as a resource in your project there is also this:

picPreview.Image = Properties.Resources.ImageName;

Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.

*Resources are located by going to: Project --> Properties --> Resources

Serpentine answered 18/12, 2020 at 2:17 Comment(0)
C
1

You can use the ImageLocation property of pictureBox1:

pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";
Categorize answered 15/10, 2019 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.