Peter
Peter

Reputation: 33

Download dynamically generated image from ASP.NET website

I'm dynamically generating image from text, and existing image on my asp.net website.

Here is the code:

protected void Button1_Click(object sender, EventArgs e)
{
    var tytul = Request.QueryString["Tytul"];
    var tresc = Request.QueryString["Tresc"];

    var font = new Font("Verdana", 23);

    var brushForeColor = new SolidBrush(Color.Black);
    var brushBackColor = new SolidBrush(Color.FromArgb(248, 247, 182));

    var test = new Bitmap(450, 60);
    var graphicstest = Graphics.FromImage(test);
    var width = (int)graphicstest.MeasureString(tresc, font).Width;
    var height = (int)graphicstest.MeasureString(tresc, font).Height;

    while (width > 450)
    {
        height = height + 25;
        width = width - 450;
    }

    var heightall = height + 40 + 30 + 100;

    var bitmap = new Bitmap(450, heightall);
    var graphics = Graphics.FromImage(bitmap);

    var displayRectangle = new Rectangle(new Point(0, 0), new Size(450, 40));
    graphics.FillRectangle(brushBackColor, displayRectangle);

    //Define string format 
    var format1 = new StringFormat(StringFormatFlags.NoClip);
    format1.Alignment = StringAlignment.Center;

    var format2 = new StringFormat(format1);

    //Draw text string using the text format
    graphics.DrawString(tytul, font, brushForeColor, displayRectangle, format2);

    // Rysowanie drugiego boxa

    brushBackColor = new SolidBrush(Color.FromArgb(253, 253, 202));
    font = new Font("Verdana", 18);

    displayRectangle = new Rectangle(new Point(0, 40), new Size(450, height + 30));
    graphics.FillRectangle(brushBackColor, displayRectangle);

    displayRectangle = new Rectangle(new Point(0, 55), new Size(450, height + 15));


    graphics.DrawString(tresc, font, brushForeColor, displayRectangle, format2);

    graphics.DrawImage(System.Drawing.Image.FromFile(Server.MapPath(".") + "/gfx/layout/podpis.png"), new Point(0, height + 70));

    Response.ContentType = "image/png";
    bitmap.Save(Response.OutputStream, ImageFormat.Png);      
}

As you can see the bitmap is saved and showed on aspx page after postback. What I wanna do is when user click Button1, then image is generated and browser download window pops up, without saving on server or showing on page. How to do this? Please help me.

Cheers.

Upvotes: 3

Views: 2548

Answers (2)

Michael C. Gates
Michael C. Gates

Reputation: 992

After you save the file:

Response.AppendHeader("content-disposition", "attachment; filename=podpis.png" );
Response.WriteFile("yourfilepath/podpis.png");
Response.End;

Upvotes: 0

SLaks
SLaks

Reputation: 888223

You need to add a Content-Disposition header.

Upvotes: 1

Related Questions