2015-12-27 132 views
2

我正在制作一个Windows窗体应用程序以从您的PC中选择一个图像,然后使用文件路径在pictureBox1中显示图像。获取图像的大小

private void button1_Click(object sender, EventArgs e) 
{ 
    if (openFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     textBox1.Text = openFileDialog1.FileName; 
     pictureBox1.ImageLocation = openFileDialog1.FileName; 
    } 
} 

现在我想把图像的尺寸(以像素为单位)放在另一个文本框中。

这可能是我做这件事的方式吗?

回答

3

我不认为你可以设置使用ImageLocation图像时(由于PictureBox的内部处理负载)获得的大小。尝试使用Image.FromFile加载图像,并使用WidthHeight属性。

var image = Image.FromFile(openFileDialog1.FileName); 
pictureBox1.Image = image; 
// Now use image.Width and image.Height 
+0

Thanks!这工作:D – Remi

1

试试这个

System.Drawing.Image img = System.Drawing.Image.FromFile(openFileDialog1.FileName); 
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height); 
1

打开使用Image.FromFile方法

Image image = Image.FromFile(openFileDialog1.FileName); 

把图像您imagepictureBox1

pictureBox1.Image = image; 

你需要的是System.Drawing.Image类。图像的大小在image.Size属性中。但是,如果你想获得WidthHeight分开,你可以使用image.Widthimage.Height分别

然后你的其他TextBox(假设名字是textBox2)你可以简单地分配Text属性就是这样,

textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString(); 

完整代码:

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(); 
    } 
}