Reputation: 49
I'm making a little Windows Forms app to select an image from your PC, and then display the image in pictureBox1
using the filepath.
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
pictureBox1.ImageLocation = openFileDialog1.FileName;
}
}
Now I want to put the dimensions (in pixels) of the image in an other textbox.
Is this possible the way I'm doing it?
Upvotes: 2
Views: 2081
Reputation: 30813
Open the image using Image.FromFile
method
Image image = Image.FromFile(openFileDialog1.FileName);
Put your image
in the pictureBox1
pictureBox1.Image = image;
What you need is System.Drawing.Image
class. The size of the image is in the image.Size
property. But if you want to get Width
and Height
separately, you can use image.Width
and image.Height
respectively
Then in your other TextBox
(suppose the name is textBox2
) You can simply assign the Text
property like this,
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
Complete code:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
Image image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image; //simply put the image here!
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
}
}
Upvotes: 1
Reputation: 14153
I don't think that you can get the size when setting the image using ImageLocation
(As the PictureBox handles loading internally). Try loading the image using Image.FromFile
, and using the Width
and Height
properties of that.
var image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image;
// Now use image.Width and image.Height
Upvotes: 3
Reputation: 28672
Try this
System.Drawing.Image img = System.Drawing.Image.FromFile(openFileDialog1.FileName);
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);
Upvotes: 1