问题描述:
new Bitmap(“xxx.png”) 导致如下错误。
文件“xxx.png”正由另一进程使用,因此该进程无法访问此文件。
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at FrameworkLib.Common.Utils.FileUtil.Copy(String sourceFilePath, String destFilePath) in E:\work\Framework\Common\Utils\FileUtil.cs:line 681
at Turbox_CCDS.View.Controls.DlgPositionTemplate.btnLoadImage_Click(Object sender, EventArgs e) in E:\work\Framework\View\Controls\DlgPositionTemplate.cs:line 1065
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
解决方法:
图像缺陷检测定位等场景建议使用方法二,若不考虑图像质量可使用方法一
方法一:
会改变图的位深度,可能导致图片质量变差
/// <summary>
/// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
/// </summary>
/// <param name="path">图片路径</param>
/// <returns></returns>
public static Bitmap ReadImageFile(string path)
{
Bitmap bit = null;
if (!File.Exists(path))
{
return bit;
}
FileStream fs = File.OpenRead(path);
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] image = new Byte[filelength]; //建立一个字节数组
fs.Read(image, 0, filelength); //按字节流读取
Image result = Image.FromStream(fs);
fs.Close();
bit = new Bitmap(result);
return bit;
}
方法二:
图像位深度不会变化,但相对方法一性能差点
/// <summary>
/// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Bitmap ReadImageFile(string path)
{
Bitmap bit = null;
if (!File.Exists(path))
{
return bit;
}
//获取图像信息
Image img = Image.FromFile(path);
//读取文件流
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] byData = new byte[fs.Length];
fs.Read(byData, 0, byData.Length);
MemoryStream ms = new MemoryStream(byData);
bit = new Bitmap(ms).Clone(new Rectangle(0, 0, img.Width, img.Height), img.PixelFormat);
fs.Close();
img.Dispose();
return bit;
}