Windform c# pictureBox 更换背景图片

Windform c# pictureBox 更换背景图片

先初始化pictureBox的背景图片,想换背景图片,通过点击pictureBox控件区域换图片,再次打开程序背景图片是上次更换的图片
实现:
初始化pictureBox的背景图片的路径在工程下是固定的,点击pictureBox控件,使用OpenFileDialog类获取更换本地图片的路径,并更换背景图片,最后将获取到的图片通过流的方式写进初始化pictureBox的背景图片的路径。

初始化pictureBox背景图片
Image Img = Image.FromFile(Application.StartupPath + @"\Resources\Model.png");
Image bmp = new Bitmap(Img);
Img.Dispose();//FromFile()取图片会将图片锁定,无法进行写入操作,为了后面的操作,要将获取到的图片释放
pictureBox1.Image = bmp;
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
使用OpenFileDialog类获取更换本地图片的路径
private void pictureBox1_Click(object sender, EventArgs e){
	DialogResult DlgResult =  MessageBox.Show(@"Do you want to change the picture",@"Tip",
    MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
    if (DlgResult != DialogResult.OK){
    	return;
     }
     OpenFileDialog fileDialog = new OpenFileDialog();
     fileDialog.Multiselect = true;
     fileDialog.Title = "Please select file";
     fileDialog.Filter = "All Image Files(*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff)|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff";
    if (fileDialog.ShowDialog() == DialogResult.OK){
    	localFilePath = fileDialog.FileName;//返回文件的完整路
        if (Image.FromFile(localFilePath).Height <= 234 || Image.FromFile(localFilePath).Width <= 300)
        {
       		Image Img = Image.FromFile(localFilePath);
            Image bmp = new Bitmap(Img);
            Img.Dispose();
            pictureBox1.Image = bmp;
            pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
            string strpath = Application.StartupPath + @"\Resources\Model.png";
            ZoomIn_control.CopyFile(localFilePath, strpath)}
        else
        {
            MessageBox.Show(@"The picture is too large. Please select a new one", @"Warning");
         }
     }
 }
将获取到的图片通过流的方式写进初始化pictureBox的背景图片的路径
public static void CopyFile(string source, string target)
        {
            using (FileStream fsRead = File.OpenRead(source))
            {
                using (FileStream fsWrite = File.OpenWrite(target))
                {
                    byte[] buffers = new byte[1024 * 4];

                    int length = fsRead.Read(buffers, 0, buffers.Length);
                    while (length > 0)
                    {
                        Console.Write(". ");
                        fsWrite.Write(buffers, 0, length);
                        length = fsRead.Read(buffers, 0, buffers.Length);
                    }
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值