saving thumbnail, getting A generic error occurred in GDI+
I am creating thumbnails for onlin开发者_运维问答e images using:
public static string SaveThumbnail(string imageUrl, int newWidth, int newHeight, string id)
{
string uploadImagePath = "/UploadedImages/";
Stream str = null;
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(imageUrl);
HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
str = wRes.GetResponseStream();
using (var image = Image.FromStream(str, false, true))
{
Image thumb = image.GetThumbnailImage(newWidth, newHeight, () => false, IntPtr.Zero);
string pathAndName = Path.ChangeExtension(uploadImagePath + id, "thumb");
thumb.Save(pathAndName);
return pathAndName;
}
}
but im getting this error:
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Any Ideas?
Iirc this is because it likes the stream to be seekable, and network streams aren't. Try copying the stream into a MemoryStream first (or a temp FileStream if huge), and work from that (remembering to set the position back to 0 before reading from it).
using(var ms = new MemoryStream()) {
str.CopyTo(ms); // a 4.0 extension method
ms.Position = 0;
// TODO: read from ms etc
}
In the case of a FileStream, you may find WebClient.DownloadFile more convenient. Ditto WebClient.DownloadData for the in-memory approach.
GDI+ error occurs when GDI can not allocate memory to do image processing. This happens when images are quite big and ASP.NET worker process limits memory used by entire process.
We created a self hosted wcf service which accepts file path and returns resized file path, this service is inside windows service which has its own process and does not have memory constraints like ASP.NET . Inside ASP.NET, we store file in temp path, and call resizer service with same path and we can then access our resized image.
Basically we have transferred the workload of resizing from ASP.NET app to windows service, and communication between ASP.NET and windows service is limited to same host.
精彩评论