Search code examples
c#databasephotodisplay

Display picture from database


I have a database with a photo column, I am trying to display it on a website. I am coding in Visual studio 2019. It's an MVC project in c#

The two photos show what I got given. The link from the second picture doesn't go anywhere

Photo1

Photo2


Solution

  • There are 2 possibilities:

    1st option:

    Store the path of the image in your database and dynamically set the src of an <img>

    2nd option:

    Save the image data in your database and reconstruct it on load, your <img> src has to be a controller action that loads, constructs and returns the image.

    Edit

    Quick example for option 2:

    In your cshtml define your image like this:

    <img src="@Url.Action("GetFromDB", "Image", new { id = 1234 })" />
    

    Note, you can set the id of your picture dynamically, depending on your scenario. Lets say you have a user class which has a profile picture assigned, you just need to use this id.

    On the backend you need a action that handles this request, in this example in the ImageController:

    public ActionResult GetFromDB(int id)
    {
        var image = _dbContext.Find(id);
        return File(image.PictureData, image.ContentType);
    }
    

    This assumes you have a simple database model for images like this:

    class Image
    {
        [Key]
        public int ID { get; set; }
        public byte[] PictureData { get; set; }
        public string ContentType { get; set; }
    }
    

    To save your image to the database, you just need to get it's bytes and content type, for example like this:

    using (var ms = new MemoryStream())
    {
        using (var uploadedImage = Image.FromStream(formFile.OpenReadStream(), true, true))
        {
            uploadedImage.Save(ms, ImageFormat.Jpeg); // you can actually chose this yourself, depending on your scenario
        }
    
        var image = new Model.Image()
        {
            PictureData = ms.ToArray(),
            ContentType = "image/jpeg" // needs to match what you chose above
        };
        _dbContext.Pictures.Add(image);
        _dbContext.SaveChanges();
    }