我正在使用以下方法为在线图像创建缩略图:
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;
}
}
但是我得到了这个错误:
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.
异常详情:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
有什么想法吗?
Iirc 这是因为它希望流是可搜索的,而网络流不是。尝试先将流复制到 MemoryStream(如果很大,则复制到临时 FileStream),然后从那里开始工作(记住在读取之前将位置设置回 0)。
using(var ms = new MemoryStream()) {
str.CopyTo(ms); // a 4.0 extension method
ms.Position = 0;
// TODO: read from ms etc
}
对于 FileStream,您可能会发现 WebClient.DownloadFile 更方便。对于内存中方法,同上 WebClient.DownloadData。
我是一名优秀的程序员,十分优秀!