Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...