- string path1 = "E:\\1.jpg";
- string path2 = "E:\\1.bmp";
- Bitmap bmp1 = new Bitmap(path1);
- bmp1.Save(path2,ImageFormat.Bmp);
path2保存的是24位的bmp文件,但是path1 = "E:\\1.gif"; 即原来为gif文件,则path2保存的是32位的bmp文件
解决gif保存为24位bmp文件的方案:
- Bitmap bmp1 = new Bitmap(path1);
- bmp1.PixelFormat = PixelFormat.Format24bppRgb;
- Rectangle cloneRect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);
- PixelFormat format =PixelFormat.Format24bppRgb;
- Bitmap cloneBitmap = bmp1.Clone(cloneRect, format);
- cloneBitmap.Save(path2, ImageFormat.Bmp);
但是可能会出现一些错误:
1. GDI+中发生一般性错误
2. 1.jpg 正由另一个进程使用 ,该进程无法访问文件
解决方案:
- FileStream fs = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.Read);
- byte[] buffer = new byte[fs.Length];
- int length = 0;
- int ibyteRead = 0;
- do
- {
- length = fs.Read(buffer, ibyteRead, buffer.Length - ibyteRead);
- ibyteRead += length;
- }
- while (length > 0);
- MemoryStream mfs = new MemoryStream(buffer);
- fs.Close();
- fs.Dispose();
- Image bmp1 = Image.FromStream(mfs);
- bmp1.Save(path2, ImageFormat.Bmp);
- bmp1.Dispose();
- mfs.Close();
- mfs.Dispose();
原因:在Image.FromStream 方法, Image 的生存期内,必须使流保持打开,对应的文件在Image对象被Disponse前都不会被解除锁定
参考:http://believehaveoneday.blog.163.com/blog/static/12073745220104179658918/