如何调用aspx页面并让它返回图像?

时间:2010-10-06 14:41:20

标签: c# asp.net image

** * *** 根据评论编辑发布到较新的代码示例< / EM> * ** * ***

所以,要清楚,我有两个文件。第一个文件名为FinalImage.aspx,这是该页面的代码:

<html>
  <body>
    <img src="newpage.aspx" />
  </body>
</html>

newpage.aspx具有以下代码,基于Jason在以下评论中的示例:

<%@ Page Language="C#" %>

<script runat="server" language="c#">

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "image/png";
        byte[] data = System.IO.File.ReadAllBytes("http://mystatus.skype.com/smallclassic/eric-greenberg");

        Response.OutputStream.Write(data, 0, data.Length);
        Response.OutputStream.Flush(); 
        Response.End();
    }

</script>

如果我打电话给FinalImage.aspx,我会看到一张破损的图像。

如果我直接调用newpage.aspx,我会收到“不支持URI格式错误”

我认为它很接近。

此外,对于刚读这篇文章的人来说,需要这个解决方案来解决这个问题,即Skype的skype按钮没有https选项,告诉skype用户的状态。创建此代理页面将允许此操作,而不会在浏览器中导致“混合”安全警报。

5 个答案:

答案 0 :(得分:8)

所以,这是最终的工作代码:感谢大家的帮助,一点一点地追踪这一点(可以这么说......)

<%@ Page Language="C#" %>

<script runat="server" language="c#">
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "image/png";

        System.Net.WebClient wc =  new System.Net.WebClient();

        byte[] data = wc.DownloadData("http://mystatus.skype.com/smallclassic/eric-greenberg");
        Response.OutputStream.Write(data, 0, data.Length);
        Response.OutputStream.Flush(); 
        Response.End();
    }
</script>

答案 1 :(得分:3)

为了扩展Aliostad的答案,这里有一个可能对你有帮助的片段:

protected void Page_Load(object sender, EventArgs e)
{
    Response.ContentType = "image/jpeg";

    var data = // .... get the content of the images as bytes. e.g. File.ReadAllBytes("path to image");

    Response.OutputStream.Write(data, 0, data.Length);
    Response.OutputStream.Flush(); // Not sure if needed, but doesn't hurt to have it.
    Response.End();
}

不确定上述内容是否100%正确,但我最近在项目中使用了类似的东西从aspx页面返回图像。不幸的是,我现在面前没有那个代码。

答案 2 :(得分:1)

要进一步扩展(在Jason的回答中),您不希望将响应流读入StreamReader(因为结果不是文本)。你可以做什么使用aspx页面作为你需要它的页面上的图像的src。例如:

<html>
    <image src="~/MyDynamicImage.aspx"/>
</html>

由于MyDynamicImage.aspx将图像作为其响应返回,因此可以将视为图像(就像您指向静态.jpg一样)。

答案 3 :(得分:0)

您需要将内容类型设置为“image / jpg”或相关图像MIME。

            Response.ContentType = "Image/jpg";

答案 4 :(得分:0)

您可以在实现IHttpHandler的类的ProcessRequest方法中使用上面发布的代码。这比使用Page更轻量级,因为您将避免页面生命周期。

http://wiki.asp.net/page.aspx/687/http-handlers-to-handle-images/有一个例子。它比你需要的更多,但你应该能够根据你的需要进行修改。