C# new Bitmap(“xxx.png“) 文件“xxx.png”正由另一进程使用,因此该进程无法访问此文件。

问题描述:

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值