使用打开文件对话框将位图图像加载到Windows窗体中 [英] Load a bitmap image into Windows Forms using open file dialog
问题描述
我需要使用打开文件对话框以窗口形式打开位图图像(我将从驱动器中加载它).图像应适合图片框.
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();
}
推荐答案
您必须创建构造函数重载,可从磁盘上的文件加载映像.在编写代码时,您正在尝试使用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.
将代码更改为如下所示(还利用了 using
语句以确保正确处理,而不是手动调用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
集合. aspx"rel =" noreferrer> 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窗体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!