0

I'm trying to do something when I click image displayed inside pictureBox1. pictureBox is loaded with this code:

string imgpath = @"img\256.png";
pictureBox48.Image = Image.FromFile(imgpath);

Then control is released to me so I can see that the picture loaded correctly. Then i click the picture:

public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}

This doesn't work. When I debug the code I see that variable1 stay null, that is pictureBox48.ImageLocation is null. Why is that? Shouldn't it be the path to the image that is assigned there?

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
Matthew
  • 37
  • 8
  • You know that `PictureBox` could have no image location but `Image` data instead? – mrogal.ski Jan 31 '18 at 06:56
  • well, there is no pictureBox48.Image.Path or pictureBox48.Image.Location so how do i access it? – Matthew Jan 31 '18 at 07:01
  • As I've said, `PictureBox` can have no _"physical"_ location. So there's no path, location or whatever you call it. There's just a raw image data. – mrogal.ski Jan 31 '18 at 07:17
  • Ok I've solved it myself. Had to change: pictureBox48.Image = Image.FromFile(imgpath); to pictureBox48.ImageLocation = @"img\256.png"; – Matthew Jan 31 '18 at 07:20

2 Answers2

1

When dealing with Image or PictureBox I would recommend to not use something like Location or Path of the image. Assume that when the image is loaded user removes it from the hard drive and you're left with the code full of errors.

That's why you should rely on Image itself as it contains every information about the image like pixel format, width, height and raw pixel data.

I would recommend you to just copy the image, not the path to the file.

This piece of code should give you a hint:

pixtureBox48.Image = Image.FromFile(imgPath);
// above code assumes that the image is still on hard drive and is accessible,

// now let's assume user deletes that file. You have the data but not on the physical location.

Image copyImage = (Image)pictureBox48.Image.Clone();
Form3 fo = new Form(copyImage); // change .ctor definition to Form(Image copy)
fo.ShowDialog();
mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
0

You can't get the image path when you set the image using the Image property because you are assigning an Image object which can come from different sources.

Set the image using ImageLocation.

string imgpath = @"img\256.png";
pictureBox48.ImageLocation = imgpath;

When you click in the PictureBox you can get the path using the same property:

public void pictureBox48_Click(object sender, EventArgs e)
{
    string variable1 = pictureBox48.ImageLocation;
    Form3 fo = new Form3(variable1);
    fo.ShowDialog();
}
Omar Muscatello
  • 1,256
  • 14
  • 25