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
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With