user2007841
user2007841

Reputation: 45

Writing a dynamically created bitmap to a panel (or any other control)

Right now I have the following code, which works fine to display my dynamically created image in the web page, but it overwrites whatever controls there were. How do I display the image inside a specific control, instead?

Ideally, I would like it to be displayed inside a panel (Panel1) that I have defined on my page.

        Response.Clear();
        Response.ContentType = "image/png";
        Bitmap bmp = new Bitmap(W, H,  PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmp);

        //lots of drawing code

        using (MemoryStream ms = new MemoryStream())
        {
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ms.WriteTo(Response.OutputStream);
        }

        bmp.Dispose();
        Response.End();

As I said, this works beautifully, except that it overwrites whatever controls I have on my page with the image, while I would like to constrain it to remain inside a panel.

is there a way to achieve this?

Upvotes: 0

Views: 1258

Answers (2)

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

assume you have a page named PageA.aspx containing a panel, you need an image element, inside the panel, like this:

<asp:Image ID="Image1" 
    runat="server" 
    CssClass="w120px h120px" 
    ImageUrl='newpage.aspx' />

notice to ImageUrl Attribute...

this image sends a request to newpage.aspx to get the picture... in the page_load of newpage.aspx you need to write your MemoryStream which is containing your picture to the Response like this:

protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.ContentType = "image/png";
        Bitmap bmp = new Bitmap(W, H, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmp);

        //lots of drawing code

        using (MemoryStream ms = new MemoryStream())
        {
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            Response.BinaryWrite(ms.ToArray());
        }

        bmp.Dispose();
        Response.End();
    }

Upvotes: 0

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

you need to an image control inside your panel, and the ImageUrl attribute of that, must be set to send its request to a new page or handler, and at that page, you need to write your bitmap, i have posted solution for this ...Here...

check that

Upvotes: 2

Related Questions