簡體   English   中英

c#GDI +中發生一般錯誤

[英]c# A generic error occurred in GDI+

當我拖動圖片框中的圖像區域兩次以上並運行掃描時,出現了這個問題。 這是一個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

我知道它發生的原因是圖像已被復制。 但是我不知道如何解決。

首先,這看起來像是該主題的復制: c#Bitmap.Save GDI + Windows應用程序中發生一般錯誤

您還提出了這個問題。 據我所知,這是關於同一代碼的相同問題。

您提到這是第二次選擇區域時發生的,並且兩次都將圖像保存到同一路徑。 您還說保存時發生錯誤。

我認為這將非常有力地表明權限錯誤。 您是否嘗試過每次嘗試都保存為新文件名?

如果這是一個權限錯誤,那么您只需要處置已對該文件進行鎖定的所有資源。

那里有很多這樣的例子: 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);
    }

但是,可能還有其他問題。 如果您從流中獲取圖像,則此流需要保持打開狀態,直到完成圖像處理為止。 (當您處置圖像時,您將自動處置流。)不過,在您發布的代碼中看不到任何類似內容。

如果您正在將第三方庫用於OCR部件,則它也可能已鎖定了資源。

有關此內容的一個好地方將在這里: http : //support.microsoft.com/?id=814675

但是,從您所說的所有內容來看,聽起來似乎只是您嘗試保存到的文件有鎖定。 因此,如上所述,我將首先嘗試每次給文件重新命名。 如果不起作用,則可以開始探索其他可能性。

快速而骯臟的例子:

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

您應先解決此問題,然后再解除權限問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM