問題描述
我需要使用打開文件對話框以窗口形式打開位圖圖像(我將從驅動器加載它).圖像應適合圖片框.
I need to open the bitmap image in the window form using open file dialog (I will load it from drive). The image should fit in the picture box.
這是我試過的代碼:
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
dialog.Title = "Open Image";
dialog.Filter = "bmp files (*.bmp)|*.bmp";
if (dialog.ShowDialog() == DialogResult.OK)
{
var PictureBox1 = new PictureBox();
PictureBox1.Image(dialog.FileName);
}
dialog.Dispose();
}
推薦答案
您必須創建 Bitmap
類,使用 構造函數重載,從磁盤上的文件加載圖像.在編寫代碼時,您正在嘗試使用 PictureBox.Image
屬性,就好像它是一種方法.
You have to create an instance of the Bitmap
class, using the constructor overload that loads an image from a file on disk. As your code is written now, you're trying to use the PictureBox.Image
property as if it were a method.
將您的代碼更改為如下所示(同時利用 使用
語句來確保正確處理,而不是手動調用Dispose
方法):
Change your code to look like this (also taking advantage of the using
statement to ensure proper disposal, rather than manually calling the Dispose
method):
private void button1_Click(object sender, EventArgs e)
{
// Wrap the creation of the OpenFileDialog instance in a using statement,
// rather than manually calling the Dispose method to ensure proper disposal
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
// Create a new Bitmap object from the picture file on disk,
// and assign that to the PictureBox.Image property
PictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
當然,這不會在表單的任何位置顯示圖像,因為您創建的圖片框控件尚未添加到表單中.您需要將剛剛創建的新圖片框控件添加到表單的 Controls
集合 使用 Add
方法.請注意在此處添加到上述代碼的行:
Of course, that's not going to display the image anywhere on your form because the picture box control that you've created hasn't been added to the form. You need to add the new picture box control that you've just created to the form's Controls
collection using the Add
method. Note the line added to the above code here:
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
PictureBox1.Image = new Bitmap(dlg.FileName);
// Add the new control to its parent's controls collection
this.Controls.Add(PictureBox1);
}
}
}
這篇關于使用打開文件對話框將位圖圖像加載到 Windows 窗體中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!