c#Bitmap.Save GDI + Windows应用程序中发生一般错误 [英] c# Bitmap.Save A generic error occurred in GDI+ windows application

查看:71
本文介绍了c#Bitmap.Save GDI + Windows应用程序中发生一般错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行OCR申请.运行系统时出现此错误,系统会将picturebox3.image保存到文件夹中.

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

推荐答案

由于已经有一段时间了,我希望您能找到答案,但是我猜想您需要在设置文件格式时正在保存jpeg:

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

过去,我不记得图片框控件是否是双缓冲的,这可能是个问题(如果不是,则在渲染时可能无法出于保存目的而访问它,但是如果在设置可解决该问题的picturebox3.Image属性之前,先制作区域的副本):

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).

这篇关于c#Bitmap.Save GDI + Windows应用程序中发生一般错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆