C#winform上传图片

在窗体上添加上传图片按钮:

// 需要添加的引用
using System.IO;  // FileInfo
using System.Windows.Forms;  // OpenFileDialog


// 用到的组件: Button、PictureBox


/// <summary>
/// 上传小票Logo
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetPic_Click(object sender, EventArgs e)
{
    string strPicPath = "";  // 存储路径
    OpenFileDialog openPic = new OpenFileDialog();
    openPic.Filter = "图片文件|*.bmp;*.jpg;*.jpeg;*.png";
    openPic.FilterIndex = 1;
    //openPic.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径为初始地址                                    
    if (openPic.ShowDialog() == DialogResult.OK)
    {
        //获取用户选择的文件,并判断文件大小不能超过20K,fileInfo.Length是以字节为单位的 
        FileInfo fileInfo = new FileInfo(openPic.FileName);
        if (fileInfo.Length > 20480)
        {
            MessageBox.Show("上传的图片不能大于20K");
        }
        else
        {
            strPicPath = openPic.FileName;              
            pictureBox1.BackgroundImage = Image.FromFile(strPicPath);  // picReceiptLogo是存储图片的路径
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Simoral/article/details/81182207