Reputation: 63
I have a picturebox that will filled up by OpenFileDialog()
after that, I must render the histogram (chart) from it. I use the get
and set
property to take the image from picturebox to another class or form. But I always getting NullReferenceException. The bitmap seems not having the image after I open a image file, so it's returning nothing. I try to fill the bitmap parameter with full path of an image and it's working, but OpenFileDialog()
become pointless.
Here's my code
MainForm.cs
// button for opening image
private void openImage_Click(object sender, EventArgs e)
{
OpenFileDialog img = new OpenFileDialog();
img.Title = "Open Image File...";
img.Filter = "Image File (*.bmp, *.jpg, *.jpeg, *.png |*.bmp;*.jpg; *.jpeg;*.png";
if (img.ShowDialog() == DialogResult.OK) {
pbInput.Image = new Bitmap(img.FileName);
// blablabla
}
}
// set and get property
public Image getImage {
get { return pbInput.Image; }
set { pbInput.Image = value; }
}
OptionsForm.cs
private void hist1_Click(object sender, EventArgs e)
{
h1 = new Histogram();
h1.FormClosed += (s, a) => hist1.Enabled = true;
hist1.Enabled = false;
h1.Show();
}
Histogram.cs
public partial class Histogram : Form
{
MainForm m = new MainForm();
public Histogram()
{
InitializeComponent();
Bitmap b = new Bitmap(m.getImage);
//bla bla bla. . . . . *creating histogram code
}
}
The error message that I got:
I hope this question is clear enough. Thank you..! PS: English is not my primary language, so apologize for my grammar, etc.
Upvotes: 0
Views: 548
Reputation: 112762
Why don't you directly assign the image to your property?
public Image getImage { get; private set; } // Auto-implemented property.
like this
if (img.ShowDialog() == DialogResult.OK) {
getImage = new Bitmap(img.FileName);
pbInput.Image = getImage;
}
Btw., getImage
is not a good name for a property. GetSomething
is generally used for methods. Just call your property Image
:
public Image Image { get; private set; }
Upvotes: 0
Reputation: 4024
When you write MainForm m = new MainForm();
in your Histogram.cs
,
You create a brand new object of Form that doesn't have reference to your old form's image
What you want is to be able to access old form's object reference in your new form or better get that image3 reference in Histogram.cs
One way to do it is to pass it to the constructor
Histogram button
private void hist1_Click(object sender, EventArgs e)
{
h1 = new Histogram(this.getImage);
h1.FormClosed += (s, a) => hist1.Enabled = true;
hist1.Enabled = false;
h1.Show();
}
and then your Histogram form
public partial class Histogram : Form
{
public Histogram(Image image)
{
Bitmap b = new Bitmap(image);
}
}
This will give you the Image in the histogram form.
Upvotes: 2
Reputation: 314
You should set image to image property getImage = new Bitmap(img.FileName);
Upvotes: 0