【问题标题】:c# A generic error occurred in GDI+c# GDI+中出现一般错误
【发布时间】:2011-04-11 16:20:56
【问题描述】:

当我拖动两次以上选择图片框中的图像区域并运行扫描时,我遇到了这个问题。这是一个 OCR 系统。

区域 OCR(Tab4_Component)

    //When user is selecting, RegionSelect = true
    private bool RegionSelect = false;
    private int x0, x1, y0, y1;
    private Bitmap bmpImage;

    private void loadImageBT_Click(object sender, EventArgs e)
    {
        try
        {
            OpenFileDialog open = new OpenFileDialog();
            open.InitialDirectory = @"C:\Users\Shen\Desktop";

            open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";

            if (open.ShowDialog() == DialogResult.OK)
            {
                singleFileInfo = new FileInfo(open.FileName);
                string dirName = System.IO.Path.GetDirectoryName(open.FileName);
                loadTB.Text = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);
                bmpImage = new Bitmap(pictureBox1.Image);
            }
            
        }
        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

    //User image selection Start Point
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        RegionSelect = true;

        //Save the start point.
        x0 = e.X;
        y0 = e.Y;
    }

    //User select image progress
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        //Do nothing it we're not selecting an area.
        if (!RegionSelect) return;

        //Save the new point.
        x1 = e.X;
        y1 = e.Y;

        //Make a Bitmap to display the selection rectangle.
        Bitmap bm = new Bitmap(bmpImage);
        

        //Draw the rectangle in the image.
        using (Graphics g = Graphics.FromImage(bm))
        {
            g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
        }

        //Temporary display the image.
        pictureBox1.Image = bm;
    }

    //Image Selection End Point
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        // Do nothing it we're not selecting an area.
        if (!RegionSelect) return;
        RegionSelect = false;

        //Display the original image.
        pictureBox1.Image = bmpImage;

        // Copy the selected part of the image.
        int wid = Math.Abs(x0 - x1);
        int hgt = Math.Abs(y0 - y1);
        if ((wid < 1) || (hgt < 1)) return;

        Bitmap area = new Bitmap(wid, hgt);
        using (Graphics g = Graphics.FromImage(area))
        {
            Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
            Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
            g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
        }

        // Display the result.
        pictureBox3.Image = area;
        area.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
        singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
    }


           private void ScanBT_Click(object sender, EventArgs e)
    {
        var folder = @"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";

        DirectoryInfo directoryInfo;
        FileInfo[] files;
        directoryInfo = new DirectoryInfo(folder);
        files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);

        var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
        processImagesDelegate.BeginInvoke(files, null, null);     

        //BackgroundWorker bw = new BackgroundWorker();
        //bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        //bw.RunWorkerAsync(bw);
        //bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    }
    
    private void ProcessImages2(FileInfo[] files)
    {
        var comparableImages = new List<ComparableImage>();

        var index = 0x0;

        foreach (var file in files)
        {
            if (exit)
            {
                return;
            }

            var comparableImage = new ComparableImage(file);
            comparableImages.Add(comparableImage);
            index++;
        }

        index = 0;

        similarityImagesSorted = new List<SimilarityImages>();
        var fileImage = new ComparableImage(singleFileInfo);

        for (var i = 0; i < comparableImages.Count; i++)
        {
            if (exit)
                return;

            var destination = comparableImages[i];
            var similarity = fileImage.CalculateSimilarity(destination);
            var sim = new SimilarityImages(fileImage, destination, similarity);
            similarityImagesSorted.Add(sim);
            index++;
        }

        similarityImagesSorted.Sort();
        similarityImagesSorted.Reverse();
        similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);

        var buttons =
            new List<Button>
                {
                    ScanBT
                };

        if (similarityImages[0].Similarity > 70)
        {
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
            con.Open();

            String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
            SqlCommand cmd2 = new SqlCommand(getFile, con);
            SqlDataReader rd2 = cmd2.ExecuteReader();

            while (rd2.Read())
            {
                for (int i = 0; i < 1; i++)
                {
                    string getText = rd2["Character"].ToString();
                    Action showText = () => ocrTB.AppendText(getText);
                    ocrTB.Invoke(showText);
                }
            }
            con.Close();
        }
        else
        {
            MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }
    #endregion

我了解它发生的原因是图像已被复制。但我不知道如何解决它。

【问题讨论】:

  • 您确定这就是您收到错误的原因吗?当存在权限问题,或者您试图访问错误的图像路径时,我通常会发生这种情况。我知道发生这种情况还有很多其他原因。当您设置断点时,它在哪一行失败?
  • 就是这条线
  • 哪条线路?我敢打赌这是一个权限,或者文件未找到错误。
  • area.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");这是行。可以找到文件。我敢打赌这不是权限问题

标签: c# ocr


【解决方案1】:

首先,这看起来像是该主题的副本: c# Bitmap.Save A generic error occurred in GDI+ windows application

您还撰写了该问题。据我所知,关于相同代码的相同问题。

您提到第二次选择区域时会发生这种情况,并且两次都将图像保存到同一路径。您还说保存时发生错误。

我认为这将是权限错误的一个非常强烈的指示。 您是否尝试过每次都保存为新文件名作为测试?

如果是权限错误,那么您只需处理已锁定该文件的所有资源。

有很多这样的例子: http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/

    public void Method1()
    {
        Image img = Image.FromFile(fileName);
        Bitmap bmp = img as Bitmap;
        Graphics g = Graphics.FromImage(bmp);
        Bitmap bmpNew = new Bitmap(bmp);
        g.DrawImage(bmpNew, new Point(0, 0));
        g.Dispose();
        bmp.Dispose();
        img.Dispose();

        //code to manipulate bmpNew goes here.

        bmpNew.Save(fileName);
    }

但是可能还有其他问题。如果您从流中获取图像,则此流需要保持打开状态,直到您完成图像处理。 (当您处置图像时,您将自动处置流。) 不过,我在您发布的代码中看不到类似的内容。

如果您将第 3 方库用于 OCR 部分,它也可能会锁定资源。

阅读这篇文章的好地方是: http://support.microsoft.com/?id=814675

但是,从您所说的所有内容来看,您尝试保存的文件听起来像是被锁定了。 如上所述,我将首先尝试每次给文件一个新名称。如果它不起作用,那么您可以开始探索其他可能性。

快速而肮脏的例子:

area.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic-" + Guid.NewGuid().ToString() + @".jpg");

您应该在解决权限问题之前尝试此操作。

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多