Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array to image and display in Razor View

I am using EF 4.1 Code First and for the sake of simplicity, let's say I have the following Entity class:

public class Person {     public int Id { get; set; }     public string Name { get; set; }     public Byte[] Image { get; set; } } 

I have managed to create a working Create View that allows the Addition of a Person object into the Database.

But when I come to display the details for a Person, I get stuck on displaying the image. After doing some research, I have the following:

// To convert the Byte Array to the author Image public FileContentResult getImg(int id) {     byte[] byteArray = DbContext.Persons.Find(id).Image;     return byteArray != null          ? new FileContentResult(byteArray, "image/jpeg")          : null; } 

And in the View where I am attempting to list the Person details, I have the following to get the Image to display:

<img src="@Html.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" /> 

However the above is not working, my image source [src] attribute returns empty.

like image 526
J86 Avatar asked Sep 26 '11 20:09

J86


People also ask

How do I display an image in a byte array?

//ImageConverter Class convert Image object to Byte Array. byte[] bytes = (byte[])(new ImageConverter()). ConvertTo(img, typeof(byte[])); //Convert Byte Array to Image and display in PictureBox.

What is razor view in MVC?

A view is an HTML template with embedded Razor markup. Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.

What is Razor syntax MVC 5?

ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

What is razor in asp net?

What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.


1 Answers

There's an even easier way of doing this if you already happen to have the image loaded in your model:

<img src="data:image;base64,@System.Convert.ToBase64String(Model.Image)" /> 

Doing this way you do not need to go to the server again just to fetch the image byte[] from the database as you're doing.

like image 64
Leniel Maccaferri Avatar answered Sep 19 '22 16:09

Leniel Maccaferri