gpt4 book ai didi

c# - 使用打开文件对话框将位图图像加载到 Windows 窗体中

转载 作者:可可西里 更新时间:2023-11-01 03:12:13 25 4
gpt4 key购买 nike

我需要使用打开文件对话框在窗口形式中打开位图图像(我将从驱动器加载它)。图片应适合图片框。

这是我试过的代码:

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 class 的实例, 使用 constructor overload从磁盘上的文件加载图像。现在编写代码时,您正在尝试使用 PictureBox.Image 属性,就好像它是一个方法

将您的代码更改为如下所示(同时利用 using statement 确保正确处理,而不是手动调用 Dispose 方法):

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 collection 中。使用 Add method .请注意在此处添加到上述代码的行:

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

关于c# - 使用打开文件对话框将位图图像加载到 Windows 窗体中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6122984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com