Rendering an Image on an ASP.NET MVC Webpage from a Bitmap Object

I have code that generated a Qr image in a .NET Bitmap object. The code that generates this is called when a button is clicked on the page, for example:

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

This is the method in the MVC for the page.

When you click the button, an image is created, and we again go to the page.

So, from here, what steps do I need to take to output this bitmap to my web page (.cshtml file). Whereas I use ASP.NET MVC.

One thing I've seen on the Internet is that people saved the image in Response.OutputStream. I'm not quite sure if this applies to ASP.NET MVC.

thanks

+5
source share
1 answer

The controller action should 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 opinion, you can do something like this

 <img src="@Url.Action("GenerateQrCode")" alt="qr code" /> 
+5
source

All Articles