Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering an image onto an ASP.NET MVC web page from a Bitmap object

I have code which has generated an image of a Qr Code into the .NET Bitmap object. The code which generates this is called when a button is pressed on the page, like so:

    public ActionResult GenerateQrCode()
    {
        Bitmap qrCodeImage = Generate();
        return RedirectToAction("QrCodeGenerator");
    }

It's a method in an MVC controller for the page.

When the button is pressed, an image is generated, and we are navigated back to the page.

So from here, what steps do I need to take to output this bitmap image to my web page (a .cshtml file). Bearing in mind that I am using ASP.NET MVC.

One thing I seen online is that people were saving the image to the 'Response.OutputStream'. I'm not quite sure if that is relevant to ASP.NET MVC.

Thanks

like image 287
Ciaran Gallagher Avatar asked Dec 09 '12 23:12

Ciaran Gallagher


1 Answers

The controller action need to return a FileStreamResult. This is how you do it

public static byte[] ConvertToByteArray(this Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

public ActionResult GenerateQrCode()
{
   Bitmap qrCodeImage = Generate();
   //write your own methode to convert your bit map to byte array, here is a link
   //http://stackoverflow.com/questions/7350679/convert-a-bitmap-into-a-byte-array-in-c
   byte[] byteArray = qrCodeImage.ConvertToByteArray();
   return File(byteArray, "image/jpeg");
} 

And in your view, you can do something like this

<img src="@Url.Action("GenerateQrCode")" alt="qr code" />
like image 109
Jack Avatar answered Oct 14 '22 01:10

Jack