使用打开文件对话框将位图图像加载到 Windows 窗体中
我需要使用打开文件对话框在窗口窗体中打开位图图像(我将从驱动器加载它)。图像应适合图片框。
这是我尝试过的代码:
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();
}
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.
Here is the code I tried:
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您必须创建
位图
类,使用加载图像的构造函数重载从文件中在磁盘上。现在编写代码时,您尝试使用PictureBox.Image
属性,就像它是方法一样。将您的代码更改为如下所示(还利用
使用 语句
以确保正确处理,而不是手动调用
Dispose
方法):当然,这不会在表单上的任何位置显示图像,因为您拥有的图片框控件创建的内容尚未添加到表单中。您需要将刚刚创建的新图片框控件添加到表单的
Controls
集合 使用添加
方法。请注意此处添加到上述代码的行: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 thePictureBox.Image
property as if it were a method.Change your code to look like this (also taking advantage of the
using
statement to ensure proper disposal, rather than manually calling theDispose
method):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 theAdd
method. Note the line added to the above code here:工作正常。
试试这个,
Works Fine.
Try this,
您应该尝试:
Dock
属性设置为Fill
(如果您希望图像填充表单)SizeMode
的图片框到StretchImage
最后:
You should try to:
Dock
property of picturebox toFill
(if you want image to fill form)SizeMode
of picturebox toStretchImage
Finally:
您也可以尝试这样,
PictureBox1.Image = Image.FromFile("" 或
You, can also try like this,
PictureBox1.Image = Image.FromFile("<your ImagePath>" or <Dialog box result>);
PictureBox.Image 是一个属性,而不是一个方法。你可以这样设置:
PictureBox.Image is a property, not a method. You can set it like this:
您可以尝试以下操作:
You can try the following:
这很简单。只需添加:
It's simple. Just add: