views:

144

answers:

3

I'm drawing an image and outputing it to web page using the following code:

Bitmap image = new Bitmap(350, 350);
Graphics g = Graphics.FromImage(image);
// code using g to draw image here
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

This works fine. Now I'd like to add a some text to the output (javascript). However, when I do* either the text isn't displayed or image comes out as garbage.

What's the proper way to do it?

(*- I changed the contenttype and used reponse.write. Also tried writing a byte array of text to the outputstream.)

+3  A: 

You need to respond with HTML that has your Javascript and an <img> tag that causes another request where you respond with this image.

Probably change the <img> that is requesting this image to an <iframe> with src set to the request.

Alternatively, it could be a <script> tag that you return JavaScript to and have it add an img to the DOM.

Lou Franco
I can reference the image in the img tag like this <img scr="drawImage.aspx"> in another page?
Booji Boy
sure you can do this. see my answer.
Henry Gao
+2  A: 

If you still want to do this in one request, then http://danielmclaren.net/2008/03/embedding-base64-image-data-into-a-webpage might be the best way to do it. It involves base64 encoded data right into the src attribute of the img tag. i.e.

<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." />
hova
This works well but not supported by all browsers so make sure to test beforehand.
JamesEggers
I thought doing this but I couldn't find a resource on how to do it that way. Thanks!
Booji Boy
+1  A: 

you can write a separate file called imageGrab.aspx for your image code and call this one in another file with javascript. It should work fine. For example

<img border=0 height=150 src='ImageGrab.aspx?seqid=3'>

imageGrab.aspx.cs will looks like

public partial class ImageGrab : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            byte[] byteData = new byte[0];

            // fetch the value of parameter into the byte array

            string seq_id = Request.QueryString["seqid"];

            if (string.IsNullOrEmpty(seq_id))
            {
                seq_id = "214";
            }


            byteData = DBManager.GetBinaryData(seq_id);

            Response.Clear();

            Response.ContentType = "image/jpeg";
            Response.BinaryWrite(byteData);
            Response.End();
        }
        catch (Exception exc)
        {
            Response.Write(exc.Message);
        }
    }

}
Henry Gao