Majid Dehnamaki
Majid Dehnamaki

Reputation: 174

convert varbinary to img and show image in mvc4

I write this code for save image in my datebase:

public ActionResult Create(Slider slider)
    {
        if (ModelState.IsValid)
        {
            int Len = Request.Files[0].ContentLength;
            byte[] fileBytes = new byte[Len];
            Request.Files[0].InputStream.Read(fileBytes, 0, Len);
            slider.SliderImage = fileBytes;
            db.Slider.Add(slider);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(slider);
    }

How I can change varbinary to image for showing my data?

Upvotes: 0

Views: 3187

Answers (2)

serene
serene

Reputation: 685

Convert your array of bytes to base64 string and display it as following Code to convert byte array to base 64 string

 public static string ToBase64ImageString(this byte[] data)
        {
            return string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(data));
        }

To display it as image you can use following code

<img src='@Model.SliderImage.ToBase64ImageString()' />

Dont forget to use the namespace of extension method in your view.

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

As far as i m understanding your problem,in order to show images in asp.net mvc below code will work:-

 public ActionResult DownloadFile(int fileId)
 {
   SliderEntities db = new SliderEntities ();

   var content = db.Slider.Where(m => m.ID == fileId).FirstOrDefault();

   byte[] contents = (byte[])content.SliderImage;  //here varbinary to byte conversion will take place.

   return File(contents, "image/jpg");  //here instead of 'jpg' you can return any image format. 
}

Upvotes: 0

Related Questions