【发布时间】:2009-11-21 03:05:14
【问题描述】:
我正在尝试获取要编码为 WordML 文档的图像。此函数的原始版本使用文件,但我需要更改它以获取使用 aspx 页面动态创建的图像。我已经修改了代码以使用 HttpWebRequest 而不是 WebClient。问题是我认为页面请求没有得到解决,因此图像流无效,当我调用 Image.FromStream 时生成错误“参数无效”。
public string RenderCitationTableImage(string citation_table_id)
{
string image_content = "";
string _strBaseURL = String.Format("http://{0}",
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped));
string _strPageURL = String.Format("{0}{1}", _strBaseURL,
ResolveUrl("~/Publication/render_citation_chart.aspx"));
string _staticURL = String.Format("{0}{1}", _strBaseURL,
ResolveUrl("~/Images/table.gif"));
string _fullURL = String.Format("{0}?publication_id={1}&citation_table_layout_id={2}",
_strPageURL, publication_id, citation_table_id);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fullURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream image_stream = response.GetResponseStream();
// Read the image data
MemoryStream ms = new MemoryStream();
int num_read;
byte[] crlf = System.Text.Encoding.Default.GetBytes("\r\n");
byte[] buffer = new byte[1024];
for (num_read = image_stream.Read(buffer, 0, 1024); num_read > 0; num_read = image_stream.Read(buffer, 0, 1024))
{
ms.Write(buffer, 0, num_read);
}
// Base 64 Encode the image data
byte[] image_bytes = ms.ToArray();
string encodedImage = Convert.ToBase64String(image_bytes);
ms.Position = 0;
System.Drawing.Image image_original = System.Drawing.Image.FromStream(ms); // <---error here: parameter is not valid
image_stream.Close();
image_content = string.Format("<w:p>{4}<w:r><w:pict><w:binData w:name=\"wordml://{0}\">{1}</w:binData>" +
"<v:shape style=\"width:{2}px;height:{3}px\">" +
"<v:imagedata src=\"wordml://{0}\"/>" +
"</v:shape>" +
"</w:pict></w:r></w:p>", _word_image_id, encodedImage, 800, 400, alignment.center);
image_content = "<w:br w:type=\"text-wrapping\"/>" + image_content + "<w:br w:type=\"text-wrapping\"/>";
}
catch (Exception ex)
{
return ex.ToString();
}
return image_content;
使用静态 URI 可以正常工作。如果我在 WebRequest.Create 方法中将“staticURL”替换为“fullURL”,则会收到错误消息。关于为什么页面请求没有完全解决的任何想法?
是的,如果我在地址栏中发布完整的 URL,它会很好地解析并显示图像。
【问题讨论】:
-
所以您的
staticURL指的是GIF 格式的文件。fullURL指的是什么?可能不是有效的图像格式? -
您返回什么错误?您确定 HttpWebRequest 使用的网址与您在浏览器中粘贴的网址完全相同吗?尝试使用您的 HttpWebRequest 应用程序 (ferozedaud.blogspot.com/2009/08/tracing-with-systemnet.html) 获取跟踪日志并查看它的内容。
-
使用 StreamReader,我能够确定响应中包含的内容是用户的默认登录页面。似乎是某种权限问题,但我原以为 WebRequests 会使用已登录用户提供的权限?有人对此有见解吗?
标签: c# url dynamic httpwebrequest