I am getting the error “Generic error occurred in GDI+” in my sample code below. What I do is that I make a request to get response for many jpeg files available at live site.
When I get response, I save the file to my application’s local folder
and converting these images to binary (bytes of array) so that I can save it into database.
private byte[] GetBinaryImageData(string imgURL)
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(imgURL);
WebResponse response = Request.GetResponse();
Stream str = response.GetResponseStream();
System.Drawing.Image objTempImg = System.Drawing.Image.FromStream(str);
objTempImg.Save(FileName, ImageFormat.Jpeg);
FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
fileStream.Close();
return buffer;
}
i don’t get this error for all images, but it occurs for some of images. Anybody know the solution? I have already spent 2 days to oversome this
If I had to guess; it is having problems with handles occasionally, for the reason that you aren’t disposing things correctly. This is especially important for things like GDI+. Introduce a few
usingstatements to your code, since pretty much all of those objects areIDisposable:(note I changed your file-reading code too, since it was hugely unreliable; it is incorrect to assume that
Stream.Readactually reads all the data; you are supposed to check the return value and loop; but since you want it all,File.ReadAllBytesis easier).