错误:在保存图像时发生GDI+通用错误。

4

当我尝试保存图片时,出现以下错误:A generic error occurred in GDI+。我搜索了这个错误,并检查了该文件夹的写入权限,还检查了图像文件是否被其他任何东西(包括我的代码)使用。但是,当我尝试保存图片时,仍然遇到相同的错误。请问问题出在哪里?

public partial class AdsMaster : Form
    {
        OpenFileDialog ofd=null;
        public AdsMaster()
        {
            InitializeComponent();
        }

    private void browseButton_Click(object sender, EventArgs e)
    {
        ofd = new OpenFileDialog();
        ofd.Filter = "image files|*.jpg;*.jpeg;*.gif;*.png;*.bmp";
        DialogResult dr = new DialogResult();
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            Image img = new Bitmap(ofd.FileName);//create the bitmap
            string imgName = ofd.SafeFileName;
            txtImagePath.Text = imgName;
            pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
            ofd.RestoreDirectory = true;
            img.Dispose();
        }
    }

    private void saveImage_Click(object sender, EventArgs e)
    {
        String str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        string path = str + "\\Image\\";
        Image img = new Bitmap(ofd.FileName);
        string imgName = ofd.SafeFileName;
        try
        {
               img.Save(path + imgName); //getting error at this line 
               MessageBox.Show("Image is saved");
               img.Dispose();  // dispose of your image                   
        }
        catch(Exception err)
        {
            MessageBox.Show(err.Message.ToString());
        }

      }        
} 

请在此处查看解决方案:https://dev59.com/gXNA5IYBdhLWcg3wNa6T?rq=1 - Mathew Thompson
你是不是尝试将图像保存到它所在的同一文件中(图像文件是否在应用程序目录中)? - Rotem
我尝试从另一个文件夹保存它,仍然得到相同的错误。 - Durga
2个回答

4

我认为这里的问题可能是由于在调用原始图像时放置了锁定。

Image img = new Bitmap(ofd.FileName);

以下内容应该可以解决问题。
private void saveImage_Click(object sender, EventArgs e)
{
    string str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    string path = str + "\\Image\\";
    string imgName = ofd.SafeFileName;

    try
    {
        File.Copy(ofd.FileName, path + imgName);

        MessageBox.Show("Image is saved");
    }
    catch (Exception err)
    {
        MessageBox.Show(err.Message.ToString());
    }
}        

谢谢你,帮了我大忙!虽然我只需要从现有的位图中创建一个新的位图。 - Kyle
https://dev59.com/gXNA5IYBdhLWcg3wNa6T#33324011 - Gaurang s

0

我通过更改文件名和路径来解决这个错误,将文件存储到新的位置。 你需要检查其中一个:

1- 文件名应该不同/不应与已经存在于新文件/图像要存储的位置上的其他文件名匹配。

2- 从操作系统驱动器中更改新文件的(保存)位置。 尽量避免将新文件/图像存储在已经安装操作系统的驱动器上。

以下代码对我有效:

         IWebdriver driver;
         driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32"); 
         driver.Navigate().GoToUrl("http://www.gmail.com");
         driver.Manage().Window.Maximize();

         Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接