Okay, i googled the problem and searched here in Stackoverflow as well and i can't find the solution, too many where it is a simple solution. I load images from a database and save them as JPG localy in a Directory. Most of the images work and save correctly, but some give the "A generic error occurred in GDI+"-Error.
Here My Code:
using (var encoderPara = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qual))
using (var paras = new EncoderParameters(1))
using (var conn = new SqlConnection(conn_str))
using (var cmd = new SqlCommand(cmd_str,conn))
{
paras.Param[0] = encoderPara;
conn.Open();
using (var reader = cmd.ExecuteReader())
while (reader.Read())
if (!reader.IsDBNull(reader.GetOrdinal("Image")))
{
var img = $"{reader["Order"]}_{reader["SubOrder"]}.jpg";
var P = Path.Combine(BasePath, img);
if (!File.Exists(P))
try
{
using (var MS = new MemoryStream((byte[])reader["Image"]))
using (var Img = Image.FromStream(MS))
using (var ImgJPG = new Bitmap(Img.Width, Img.Height))
using (var g = Graphics.FromImage(ImgJPG))
{
g.Clear(Color.White);
g.DrawImage(Img, new Point(0, 0));
ImgJPG.Save(P, JPG_Encoder, paras);
WriteinLog($"Image created: {P}");
}
}
catch (Exception ex)
{
WriteinLog(string.Format("{1}{0}{0}{2}{0}{0}{3}{0}{0}{4}{0}{0}{5}{0}{0}{6}", Environment.NewLine, $"Error {img}", ex.GetType().FullName, ex.Message, ex.Source, ex.StackTrace, ex.TargetSite));
}
}
}
I would think that the error is somewhere in innermost using-blocks, since it seems to go there without problem. So I removed the usings and tried to save the Image as is and still the GDI+ error came.
It then looked like this:
var MS = new MemoryStream((byte[])reader["Meta"]);
var Img = Image.FromStream(MS);
{
Img.Save(P);
WriteinLog($"Image created: {P}");
}
My main problem is, that it works with most of the Images, only some are the exception, but if it where a codec-error it would trigger a error sooner. It can't be that MS or Image are disposed, since they are together in the using block and i tried to remove the usings. It can't be that the File exists and is in use, because i check for that.
Okay, i wrote the Last sentence "It can't be that the File exists and is in use, because i check for that." and realized that not all Subordernumbers are numbers in the Database, so replaced the filename with a increasing integer and it works.
So the "A generic error occurred in GDI+"-Error when the Path is wrong. Good to know and look out for.
I already wrote all of this, so i post it with the answer as thanks for beeing my Rubber-Ducky and hope it helps someone else.