C# Bitmap保存的问题,eg:GDI+中发生一般性错误 .jpg 正由另一个进程使用 ,该进程无法访问文件

[csharp]  view plain  copy
  1. string path1 = "E:\\1.jpg";  
  2. string path2 =  "E:\\1.bmp";  
  3. Bitmap bmp1 = new Bitmap(path1);  
  4. bmp1.Save(path2,ImageFormat.Bmp);  

path2保存的是24位的bmp文件,但是path1 = "E:\\1.gif"; 即原来为gif文件,则path2保存的是32位的bmp文件

解决gif保存为24位bmp文件的方案:

[csharp]  view plain  copy
  1. Bitmap bmp1 = new Bitmap(path1);  
  2. bmp1.PixelFormat = PixelFormat.Format24bppRgb;  
  3. Rectangle cloneRect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);  
  4. PixelFormat format =PixelFormat.Format24bppRgb;  
  5. Bitmap cloneBitmap = bmp1.Clone(cloneRect, format);  
  6. cloneBitmap.Save(path2, ImageFormat.Bmp);  

但是可能会出现一些错误:

1. GDI+中发生一般性错误

2. 1.jpg 正由另一个进程使用 ,该进程无法访问文件


解决方案:

[csharp]  view plain  copy
  1. FileStream fs = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.Read);  
  2. byte[] buffer = new byte[fs.Length];  
  3. int length = 0;  
  4. int ibyteRead = 0;  
  5. do  
  6. {  
  7. length = fs.Read(buffer, ibyteRead, buffer.Length - ibyteRead);  
  8. ibyteRead += length;  
  9. }  
  10. while (length > 0);  
  11. MemoryStream mfs = new MemoryStream(buffer);  
  12. fs.Close();  
  13. fs.Dispose();  
  14. Image bmp1 = Image.FromStream(mfs);  
  15. bmp1.Save(path2, ImageFormat.Bmp);  
  16. bmp1.Dispose();  
  17. mfs.Close();  
  18. mfs.Dispose();  


原因:在Image.FromStream 方法, Image 的生存期内,必须使流保持打开,对应的文件在Image对象被Disponse前都不会被解除锁定

参考:http://believehaveoneday.blog.163.com/blog/static/12073745220104179658918/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值