c#如何创建一个简单的图片加载程序

0 阅读1分钟

1.思路

1.要实现功能: 浏览路径 选择图片 加载图片

2.UI设计 用到的主要控件:
浏览:一个button点击进行路径选择,一个只读textbox进行路径显示
显示:一个只读的picturebox将图片显示出来
布局: 分为上下两部分,上面部分进行图片选择,下部分图片显示,使用layout固定位置
3.事件 浏览button——浏览电脑文件夹并选择.jpg/.png文件 加载图片并显示到picturebox中

2.代码实现

{
    public partial class MainForm : Form
    {
        private const string DialogName = "请选择图片";
        private string mPicturePath = null;
        public MainForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void button_Browse_Click(object sender, EventArgs e)
        {
            //点击进行文件的浏览
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Title = DialogName;
                openFileDialog.Filter = "图片文件(*.jpg);(*.png)|*.jpg;*.png";
                openFileDialog.Multiselect = false;
                openFileDialog.RestoreDirectory = true;

                if(openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    mPicturePath = openFileDialog.FileName;
                    textBox_FilePath.Text = mPicturePath;
                    try
                    {
                        pictureBox_Picture.Image = System.Drawing.Image.FromFile(mPicturePath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"预览失败:{ex.Message}", "提示");
                    }
                }
                else
                {
                    MessageBox.Show("你取消了图片选择", "提示");
                }
            }
        }
    }
}

3.演示

image.png