Asp.Net MVC Display image from byte array

In this tutorial i am going to explain about Asp.Net MVC Display image from byte array using C#.Net and VB.Net. In my previous tutorial i have explained about

Implementation :

Now we will see the implementation of Asp.Net MVC Display image from byte array using C#.Net and VB.Net.

  1. Open visual studio and create a new mvc project.
  2. Once the project is loaded right click on controllers folder and add new controller.
  3. Create Images folder in your project and add a sample image.
  4. Now open the DemoController and add GetImageFromByteArray action method.
  5. Within the action method place the code given below(Below i have given entire controller code.)

C#.Net Code:



VB.Net Code:

Now let me explain what is there in the code.

  1. I read the image from the folder into imgPath local variable
  2. In the second step i have converted the image into byte array using ReadAllBytes method.
  3. And then i have converted byte array into base 64 string format using Convert.ToBase64String method.
  4. Now I have appended data:image/png;base64 at the beginning of base64 string so that the browser knows that the src attribute value itself contains the image data.
  5. Finally i have assigned this image data in the viewbag and returned it to view.

Now add a new view to GetImageFromByteArray action method. And add a image view. We can directly assign the imagedata from viewbag to src attribute of the image tag like below.

Output:

Now if you run the program you can see the output of Asp.Net MVC Display image from byte array using C#.Net and VB.Net.

Asp.Net MVC Display image from byte array

Now if you look into the source of the page you can see the base 64 string rendered as image.

Output of Asp.Net MVC Display image from byte array

Conclusion:

Hope you learned Asp.Net MVC Display image from byte array using C#.Net and VB.Net. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Tags:

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!