2

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???

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216

2 Answers2

8

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 })" />
Iman Nemati
  • 427
  • 3
  • 11
0

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.

sed
  • 5,431
  • 2
  • 24
  • 23