Search code examples
databaseasp.net-mvc-4varbinary

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?


Solution

  • 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.