使用打开文件对话框将位图图像加载到Windows窗体中 [英] Load a bitmap image into Windows Forms using open file dialog

查看:167
本文介绍了使用打开文件对话框将位图图像加载到Windows窗体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您必须创建

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆