2015-12-27 131 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(); 
    } 
}