How can I use ImageFormatConverter.ConvertFromString to convert a string containing HTML response to an image?

This is what I achieved:

in pageload

{
    panelmain.Controls.Add(abc);
    panelmain.Controls.Add(grid1);
    string toexport;
    toexport = RenderControl(panelmain);

    ImageFormatConverter imgc = new ImageFormatConverter();
    System.Drawing.Image convertedimage;
    convertedimage = (System.Drawing.Image) imgc.ConvertFromString(toexport);
    Response.ContentType = "image/jpg";
    Response.AppendHeader("Content-Disposition", "inline;filename=tm.jpeg");
    Response.BufferOutput = true;
    Response.Charset = "utf-8";
    Response.Write(convertedimage);
    Response.End();
    //form1.Controls.Add(abc);
}

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();
}

The error is:

ImageFormatConverter cannot convert from System.String.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You may have misinterpreted the documentation of ConvertFromString here, explanation:

You are using an ImageformatConverter class which inherits and overrides TypeConverter. This means that ConvertFromString is inherited from the superclass, but because there’s no way you can convert a string to an image (unless you have a vivid imagination), this method always returns null (according to documentation), or throws a NotSupportedException. This is the default behavior of the base class and an overriding class can define custom behavior, which in your case, has not been done.

To convert from a string you will first have to define what you want. I.e., is the string a path to an image? Is it a piece of text and you want to render an image from that? Is it a Base64 encoded string that contains an image? Is it a rendered HTML page or does it contain an RTF document? Once you have an answer to these questions, you can choose the correct converter or image constructor.

EDIT: because your question seems to be about rendering HTML as an image, check out this post at SO, as also mentioned by rchern above.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x