Download image from server memory

8

I have an Asp.Net MVC project where I generate an image in memory and would like to download it.

See a snippet of code:

Image imagem = default(Image);

using (Bitmap b = new Bitmap(bitmapWidth, bitmapHeight))
{
    using (Graphics g = Graphics.FromImage(b))
    {
        g.Clear(Color.Red);

        var font = new Font("Arial", 50, FontStyle.Bold);
        g.DrawString("Stackoverflow", font, Brushes.White, posicaoX, posicaoY);
    }

    using (MemoryStream stream = new MemoryStream())
    {
        b.Save(stream, ImageFormat.Jpeg);
        imagem = Image.FromStream(stream);
    }
}

using (System.Net.WebClient client = new System.Net.WebClient())
{
    client.DownloadFile(imagem); // Não sei bem como posso fazer o Download.
}
    
asked by anonymous 01.12.2015 / 18:52

1 answer

6

In your Controller , create an Action like this:

    public FileResult Imagem()
    {
        /* Carregue o stream antes. */
        return File(stream, "image/jpeg");
    }

Or, adapting your logic:

public FileResult Imagem()
{
    Image imagem = default(Image);

    using (Bitmap b = new Bitmap(bitmapWidth, bitmapHeight))
    {
        using (Graphics g = Graphics.FromImage(b))
        {
            g.Clear(Color.Red);

            var font = new Font("Arial", 50, FontStyle.Bold);
            g.DrawString("Stackoverflow", font, Brushes.White, posicaoX, posicaoY);
        }

        using (MemoryStream stream = new MemoryStream())
        {
            b.Save(stream, ImageFormat.Jpeg);
            imagem = Image.FromStream(stream);
            return File(stream.ToArray(), "image/jpeg");
        }   
    }
}

EDIT

I do not know what is closing the stream , according to your comment, but I would try loading another stream to return, like this:

using (var ms = new MemoryStream())
{
    imagem.Save(ms,ImageFormat.Jpeg);
    return File(ms.ToArray(), "image/jpeg");
}
    
01.12.2015 / 18:55