How do I put an image into my picturebox using ImageLocation?

前端 未结 2 1617
天命终不由人
天命终不由人 2021-01-22 12:52

I have created a picturebox within my panel and I would like to fill it up with an image locally.

this is what I have done so far and the following code is just a small

相关标签:
2条回答
  • 2021-01-22 13:08

    if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

    PictureBox picture = new PictureBox
            {
                Name = "pictureBox",
                Size = new Size(100, 50),
                Location = new Point(14, 17),
                Image = Image.FromFile(@"c:\Images\test.jpg"),
                SizeMode = PictureBoxSizeMode.CenterImage
            };
    p.Controls.Add(picture);
    

    OR

    PictureBox picture = new PictureBox
            {
                Name = "pictureBox",
                Size = new Size(100, 50),
                Location = new Point(14, 17),
                ImageLocation = @"c:\Images\test.jpg",
                SizeMode = PictureBoxSizeMode.CenterImage
            };
    p.Controls.Add(picture);
    

    i'm not sure where you put images in your folder structure but you can find the path as bellow

     picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
    
    0 讨论(0)
  • 2021-01-22 13:27

    Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

    For example, if your .exe is located at:

    <project folder>/bin/Debug/app.exe

    The image would have to be at:

    <project folder>/bin/Image/1.jpg


    Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

    If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

    At this point the image file will be copied when you build the application and you can use

    picture.ImageLocation = @"Image\1.jpg"; 
    
    0 讨论(0)
提交回复
热议问题