如何将响应流转换为图像?

时间:2010-08-29 11:33:06

标签: c# asp.net visual-studio-2008 html-to-jpeg

请注意,此链接Render HTML as an Image无效。

在之前提出的问题中,回答说他们没有得到我想做的事情,所以这里也是完整的代码。

我只想要而不是表格,而是在页面上呈现(内容的)图像。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Text;
using System.Data;
using System.Drawing;


public partial class _Default : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{

    System.Web.UI.WebControls.Panel panelmain = new System.Web.UI.WebControls.Panel();
    System.Web.UI.WebControls.Literal abc = new System.Web.UI.WebControls.Literal();
    abc.Text = "as<br/>dasdas<br/>dasdad";


    DataSet ds = new DataSet();
    DataTable dt;
    DataRow dr;
    DataColumn idCoulumn;
    DataColumn nameCoulumn;

    dt = new DataTable();
    idCoulumn = new DataColumn("ID", Type.GetType("System.Int32"));
    nameCoulumn = new DataColumn("Name", Type.GetType("System.String"));
    dt.Columns.Add(idCoulumn);
    dt.Columns.Add(nameCoulumn);
    dr = dt.NewRow();
    dr["ID"] = 1;
    dr["Name"] = "Name1";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["ID"] = 2;
    dr["Name"] = "Name2";
    dt.Rows.Add(dr);

    ds.Tables.Add(dt);

    System.Web.UI.WebControls.GridView grid1 = new 
    System.Web.UI.WebControls.GridView();
    grid1.DataSource = ds;
    grid1.DataBind();

    panelmain.Controls.Add(abc);
    panelmain.Controls.Add(grid1);

    string toexport;
    toexport = RenderControl(panelmain);

    Byte[] bitmapData = new Byte[100000];
    bitmapData = Convert.FromBase64String(FixBase64ForImage(toexport));
    System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
    Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));

    Response.ContentType = "image/gif";
    Response.AppendHeader("Content-Disposition", "inline;filename=tm.gif");
    Response.BufferOutput = true;
    Response.Charset = "utf-8";
    Response.Write(bitImage);
    Response.End();

    }



public string FixBase64ForImage(string Image)
{
    System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);

    sbText.Replace("\r\n", String.Empty);

    sbText.Replace(" ", String.Empty);

    return sbText.ToString();
}



public string RenderControl(Control ctrl)
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    Response.Write(sb);

    return sb.ToString();



}

1 个答案:

答案 0 :(得分:1)

your previous question中,您已经收到了答案(由我提供),请参考此问题已解答的to another SO thread。该线程中的第二个答案链接到Web上的另一个页面,其中解释了启动WebBrowser对象,重新打印页面,捕获图像,将其转换为首选图像文件格式,将其保存在本地的整个过程。这不是一项简单的任务(期望花费几个小时),但也不是太难。

要重复the answer in the referred to question,请查看此WinCustomize.com article,下载来源和实验