Picturebox加载图片后在删除该图片时的报错问题的解决方法

当用Picturebox显示图片时是用的

Image.FromFile(ImageRul);这个方法来显示图片的,

如果这时想把图片给删除的话(File.Delete()),会报错,提示该图片正在使用中,

1,方法一,就是将该图片以流的方式加载进来,然后在赋给Picturebox,这样不存在删除的时候报错了。

调用的时候用:

Image.FromStream(ByteToStream(SetImageToByteArray(ImageUrl)));

下面是封装好的方法:

 

#region 将文件转换成流 //public byte[] SetImageToByteArray(string fileName, ref string fileSize) /// <summary> /// 将文件转换成流 /// </summary> /// <param name="fileName">文件全路径</param> /// <returns></returns> public byte[] SetImageToByteArray(string fileName) { byte[] image = null; try { FileStream fs = new FileStream(fileName, FileMode.Open); FileInfo fileInfo = new FileInfo(fileName); //fileSize = Convert.ToDecimal(fileInfo.Length / 1024).ToString("f2") + " K"; int streamLength = (int)fs.Length; image = new byte[streamLength]; fs.Read(image, 0, streamLength); fs.Close(); return image; } catch { return image; } } #endregion #region 将byte转换成MemoryStream类型 /// <summary> /// 将byte转换成MemoryStream类型 /// </summary> /// <param name="mybyte">byte[]变量</param> /// <returns></returns> public MemoryStream ByteToStream(byte[] mybyte) { MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length); return mymemorystream; } #endregion #region 将byte转换成Image文件 /// <summary> /// 将byte转换成Image文件 /// </summary> /// <param name="mybyte">byte[]变量</param> /// <returns></returns> public Image SetByteToImage(byte[] mybyte) { Image image; MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length); image = Image.FromStream(mymemorystream); return image; } #endregion

2,方法2:Picturebox.Load();    

 

3, 方法3:01.//显示图片 02.private void button1_Click(object sender, EventArgs e) 03.{ 04. pictureBox1.Image = Image.FromFile(@"f:/demo.gif"); 05.} 06. 07.//不显示图片并释放资源 08.private void button2_Click(object sender, EventArgs e) 09.{ 10. Image image = pictureBox1.Image; 11. pictureBox1.Image = null; 12. image.Dispose();//释放后就能正常删除 13.}  

你可能感兴趣的:(image,String,object,null,byte,button)