I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

how to convert binary data to image and display in Div Tag or img Tag?

I am converting my image to binary data and storing in binary format with this:

byte[] bytes = System.IO.File.ReadAllBytes(@"F:\Image\Img1.jpg");

My database field for storing image is: Varbinary(Max)

Now i am reading this binary data from my database and i am getting binary data.

I want to display image in this Div tag.

This is my View:

 <div class="Image-ad"></div>

My Class:

 public class ImageAdd   
 {
        public Guid ImageAddId { get; set; }
        public byte[] Image { get; set; }
 }

My Controller:

public ActionResult Index()
{
   var data=db.ImageAdd.ToList();    
   return View(db);
}

How to convert this binary data to image and display in Div Tag???

Upvotes: 2

Views: 8882

Answers (2)

Sed
Sed

Reputation: 6381

You can also use a canvas tag to load the image inside it and render it that way, we did this for previewing uploaded images in a recent project.

Upvotes: 0

Iman Nemati
Iman Nemati

Reputation: 427

Two options:

1 : add this to image div

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

and you'r done!

2: another way is to add a simple method to your controller and call it in your view to display the image tag. add this method to your controller:

public ActionResult GetImage(byte[] data) 
{
  MemoryStream ms = new MemoryStream(data)
  return File(ms.ToArray(), "image/png");
}

and in view add this line to image div:

<img src="@Url.Action("GetImage", "MyController", new { data = Model.Image })" />

Upvotes: 8

Related Questions