9

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

Ciaran Gallagher
  • 3,895
  • 9
  • 53
  • 97

1 Answers1

12

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" />
Brett Rigby
  • 6,101
  • 10
  • 46
  • 76
Jack
  • 2,600
  • 23
  • 29
  • That works nicely! Just one little though, if I still wanted to use a button to generate the image, and to return to the same page (by returning the redirect), how could I save the FileContentResult to a variable and then use it on my view? – Ciaran Gallagher Dec 10 '12 at 00:17
  • 1
    If all you want your button to do is to refresh your image, then I would suggest to use Javascript to update the image path of the image tag(maybe update with an id), that should reload your image. Saving FileContentResult to a variable, the concept is just wrong, it's like saving a Response result and use it use it view which wouldn't make sense at all. – Jack Dec 10 '12 at 00:43
  • 1
    If you think this has helped you to solve the issue, can you mark it as answer please? – Jack Dec 10 '12 at 05:31
  • 1
    Show ConvertToByteArray()? –  Sep 17 '18 at 06:27