2

我目前正在开发一个应用程序来帮助在我的工作中扫描和显示图像。

我的应用程序是用多种形式构建的,这里最重要的形式是我mainForm显示有关当前扫描的统计信息和具有不同功能的菜单条。我也有ImageViewerForm一个PictureBox显示在辅助监视器上以查看当前扫描的图像。

我正在使用 aTimer来轮询图像扫描到的文件夹。当一个新的图像被扫描并且图像被解锁时,我会把它抓成一个FileStream并显示在 中PictureBox,见下文:

public static void SetPicture(string filename, PictureBox pb)
{
    try
    {
        Image currentImage;

        //currentImage = ImageFast.FromFile(filename);
        using (FileStream fsImage = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            currentImage = ScaleImage(Image.FromStream(fsImage), new Size(pb.Width, pb.Height));

            if (pb.InvokeRequired)
            {
                pb.Invoke(new MethodInvoker(
                delegate()
                {
                    pb.Image = currentImage;
                }));
            }
            else
            {
                pb.Image = currentImage;
            }
        }
    }
    catch (Exception imageEx)
    {
        throw new ExceptionHandler("Error when showing image", imageEx);
    }
}

public static Image ScaleImage(Image imgToResize, Size size)
{
    int sourceWidth = imgToResize.Width;
    int sourceHeight = imgToResize.Height;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)size.Width / (float)sourceWidth);
    nPercentH = ((float)size.Height / (float)sourceHeight);

    if (nPercentH < nPercentW)
        nPercent = nPercentH;
    else
        nPercent = nPercentW;

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap b = new Bitmap(destWidth, destHeight);

    using (Graphics g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
    }

    return b;
}

这样,PictureBox不应锁定中显示的图像,但确实如此。问题是扫描的图像可能必须重新扫描,如果这样做,我会在尝试从扫描软件覆盖图像文件时收到共享冲突错误。

谁有我能做什么的答案?

解决方案

感谢@SPFiredrake,我有了一个解决方案来创建一个临时文件以显示在 PictureBox 中,让原始图像保持解锁状态。

public static void SetPicture(string filename, PictureBox pb)
{
    try
    {
        Image currentImage;

        //currentImage = ImageFast.FromFile(filename);
        using (FileStream fsImage = new FileStream(CreateTempFile(filename), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            currentImage = ScaleImage(Image.FromStream(fsImage), new Size(pb.Width, pb.Height));

            if (pb.InvokeRequired)
            {
                pb.Invoke(new MethodInvoker(
                delegate()
                {
                    pb.Image = currentImage;
                }));
            }
            else
            {
                pb.Image = currentImage;
            }
        }
    }
    catch (Exception imageEx)
    {
        throw new ExceptionHandler("Error when showing image", imageEx);
    }
}

public static string CreateTempFile(string fileName)
{
    if (string.IsNullOrEmpty(fileName))
        throw new ArgumentNullException("fileName");
    if (!File.Exists(fileName))
        throw new ArgumentException("Specified file must exist!", "fileName");
    string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(fileName));
    File.Copy(fileName, tempFile);

    Log.New("Temp file created: " + tempFile);

    return tempFile;
}
4

7 回答 7

4

这里的问题是图像是从 FileStream 加载的,该文件被 PictureBox 锁定,因为它持有对流的引用。您应该首先将图片加载到本地内存(通过 byte[] 数组),然后从 MemoryStream 加载图像。在您的SetPicture方法中,您应该尝试以下更改,看看它是否有效:

public static void SetPicture(string filename, PictureBox pb)
{
    try
    {
        Image currentImage;
        byte[] imageBytes = File.ReadAllBytes(filename);
        using(MemoryStream msImage = new MemoryStream(imageBytes))
        {
            currentImage = ScaleImage(Image.FromStream(msImage), new Size(pb.Width, pb.Height));
        ....
}

编辑:在我们在 Chat 中进行对话后,使用您最终使用的修复程序进行更新:

public static void SetPicture(string filename, PictureBox pb)
{
    try
    {
        Image currentImage;
        string tempFile = Path.Combine(Path.GetTempDirectory(), Guid.NewGuid().ToString() + Path.GetExtension(filename));
        File.Copy(filename, tempFile);
        //currentImage = ImageFast.FromFile(filename);
        using (FileStream fsImage = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            ...

这样您就可以使用临时文件来实际加载图片框,而原始文件保持不变(在初始副本之外)。

于 2012-05-07T13:52:50.060 回答
1

加载位图后,您将不再保留文件流,因此一切都应该正常工作。但是,如果您正在谈论加载发生的瞬间并且扫描尝试覆盖该文件 - 始终扫描到“临时”或垃圾命名文件(使用 GUID 作为名称)。扫描完成后,将该文件重命名为 JPG - 然后您的显示表单将正确选择并显示该文件。

这样,重新扫描将只涉及尝试使用“等待”多次重命名临时文件,以防止该小区域重叠。

于 2012-05-03T14:20:12.120 回答
1

你的代码对我来说很好。我拿了一个精确的副本,并用同一个图像文件反复调用它。

SetPicture(@"c:\temp\logo.png", pictureBox1);

其他东西正在锁定文件。你能分享你的电话号码吗?

于 2012-05-03T15:32:47.077 回答
0

我想你现在已经完成了你的工作。
不过,我发帖以防其他人有同样的问题。
我有同样的问题:我在 PictureBox 控件中加载图像

picture.Image = new Bitmap(imagePath);  

并在尝试移动它时

File.Move(source, destination);  

mscorlib 抛出异常:
该进程无法访问该文件,因为它正在被另一个进程使用

我在这里找到了一个解决方案(虽然在 VB.Net 而不是 C# 中)PictureBox“锁定”文件,无法移动/删除

帖子的作者克隆了原始图像,并将克隆的图像加载到PictureBox控件中。
我稍微改变了代码并想出了这个:

private Bitmap CloneImage(string aImagePath) {  
    // create original image
    Image originalImage = new Bitmap(aImagePath);

    // create an empty clone of the same size of original
    Bitmap clone = new Bitmap(originalImage.Width, originalImage.Height);

    // get the object representing clone's currently empty drawing surface
    Graphics g = Graphics.FromImage(clone);

    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed;

    // copy the original image onto this surface
    g.DrawImage(originalImage, 0, 0, originalImage.Width, originalImage.Height);

    // free graphics and original image
    g.Dispose();
    originalImage.Dispose();

    return clone;
    }

所以,我们的代码将是:

picture.Image = (Image)CloneImage(imagePath);  

这样做,我在移动文件时没有更多例外。
我认为这是一种很好的替代方法,并且您不需要临时文件。

于 2013-01-03T17:08:52.077 回答
0

这是 Jack 代码,但在 Visual Basic .NET 中,并且转换进入函数内部

 Private Function CloneImage(aImagePath As String) As Image
        ' create original image
        Dim originalImage As Image = New Bitmap(aImagePath)

        ' create an empty clone of the same size of original
        Dim clone As Bitmap = New Bitmap(originalImage.Width, originalImage.Height)

        ' get the object representing clone's currently empty drawing surface
        Dim g As Graphics = Graphics.FromImage(clone)

        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed

        ' copy the original image onto this surface
        g.DrawImage(originalImage, 0, 0, originalImage.Width, originalImage.Height)

        ' free graphics and original image
        g.Dispose()
        originalImage.Dispose()

        Return CType(clone, Image)
    End Function

所以调用将是

picture.Image = CloneImage(imagePath)

谢谢杰克,

于 2013-04-01T23:41:47.060 回答
0

MS对这个问题的回应......

对我来说工作正常...

internal void UpdateLastImageDownloaded(string fullfilename)
{
    this.BeginInvoke((MethodInvoker)delegate()
    {
        try
        {
            //pictureBoxImage.Image = Image.FromFile(fullfilename);

            //Bitmap bmp = new Bitmap(fullfilename);
            //pictureBoxImage.Image = bmp;

            System.IO.FileStream fs;
            // Specify a valid picture file path on your computer.
            fs = new System.IO.FileStream(fullfilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            pictureBoxImage.Image = System.Drawing.Image.FromStream(fs);
            fs.Close();
        }
        catch (Exception exc)
        {
            Logging.Log.WriteException(exc);
        }
    });
}
于 2016-03-18T15:56:17.237 回答
0

在尝试为我的 C# Windows 窗体找出解决方案时,我遇到了一篇有用的文章,其中提到了如何在图片框中加载图片而不“锁定”原始图片本身,而是它的一个实例。因此,如果您尝试删除、重命名原始文件或对原始文件执行任何操作,您将不会收到一条错误消息通知您“该文件正在被另一个进程使用”或其他任何内容!

这是对文章的引用

总而言之,我相信这个解决方案在处理少量图片时非常有用因为大量应用这种方法可能会导致内存不足。

于 2017-01-05T15:20:22.580 回答