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