开发者

c# Bitmap.Save A generic error occurred in GDI+ windows application

开发者 https://www.devze.com 2023-02-24 04:54 出处:网络
I am doing OCR application. I have this error when I run the system which the system will save the picturebox3.image into a folder.

I am doing OCR application. I have this error when I run the system which the system will save the picturebox3.image into a folder.

//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;


    ** ERROR occuer here!!!!!**
    area.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg"); // error line occcur

    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


Since it has been a while, I'm hoping you found your answer, but I'm going to guess that you needed to set the file format when you're saving a jpeg:

area.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

Past that, I can't remember if the picturebox control is double buffered or not which could be the problem (if it's not, you might not be able to access it for saving purposes while it is being rendered, but if you make a copy of area before setting the picturebox3.Image property that would fix that issue):

Bitmap SavingObject=new Bitmap(area);
picturebox3.Image=area;
SavingObject.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

Anyway, I hope you ended up finding your solution (considering it's been a couple months since this was posted).


This looks like a copy of this question: c# A generic error occurred in GDI+

Same code, same error, same author.

Can't see any difference. But maybe I'm missing something.

0

精彩评论

暂无评论...
验证码 换一张
取 消