Generate and Display image from Memorystream in C#

Recently I was working in Microsoft chart in MVC which returns memorystream. Instead of generate Image by taking new Action every time (which query database every time and very ridiculous) , I thought i can generate image from Memorystream, after googling some resource I found useful code to display image from memorystream using base64. Base64 data image support all major browsers. I know you will found too many articles on this topic but still i am interested to post this small but useful tip on my blog.
public string GetImageSrc(MemoryStream memoryStream)
   return "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray(), 0, memoryStream.ToArray().Length);
How to use in
<img id="img" runat="server" />
img.Src= GetImageSrc(ms); // server side
How to use in MVC
<img id="img" Src='@ViewBag.Src' />
@ViewBag.Src = GetImageSrc(ms); // server side
Hope you enjoy this time saving tip... Happy Coding !


Popular posts from this blog

12 opensource and free MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in