0

I am very new to asp.net MVC. For last two days, I am trying to show an Image in cshtml View from my SQL database.

Here is the method for getting the image from database:

public class ProfilePicture:Gateway
    {
        public byte[] ShowProfilePicture()
        {
            Query = "SELECT * FROM t_ProfilePicture WHERE UserId='" + 1 + "'";
            Command = new SqlCommand(Query, Connection);
            Connection.Open();
            Reader = Command.ExecuteReader();
            byte[] image = null;
                while (Reader.Read())
                {
                    image = (byte[])Reader["ProfilePictureFile"];
                }
            Reader.Close();
            Connection.Close();  
            return image;
        } 
    }

This is the HTML helper code for getting the byte data & convert it to base64:

@{   
    ProfilePicture aProfilePicture = new ProfilePicture();
    var image = aProfilePicture.ShowProfilePicture();
    string string64 = Convert.ToBase64String(image);
    ViewBag.profilePicture = "data:image/png;base64," + string64;    
}

And here is the <img> tag:

<img id="profilePicture" src="@ViewBag.profilePicture" alt="profilePicture" />

I almost follow all the available solutions including this. But didn't get any solution yet.

Thank's in advance for any help.

Community
  • 1
  • 1
ramzan ali
  • 471
  • 4
  • 14

2 Answers2

0

Try using Html.Raw around it; there may be some encoding going on that is causing an issue:

<img id="profilePicture" src="@Html.Raw(ViewBag.profilePicture)" alt="profilePicture" />
Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • Thank's for your answer, I just tried but did not show the image. Please provide another solution if possible. – ramzan ali Feb 02 '17 at 17:50
  • This is what I did in a solution and it worked for me, so I'm not sure why it wouldn't work for ow. So I'd ask: is the source image a PNG file type? How big is the source image, and how big is the byte array? Are you sure the stored procedure returns the correct value? – Brian Mains Feb 02 '17 at 18:01
  • The source image is a .jpg file type. The source image is 21.8KB and the byte array is: {byte[13]}. And I think it returns a correct value. Please ask if further info needed. – ramzan ali Feb 02 '17 at 18:07
  • Also check data:`image/jpeg`. But didn't solve the problem – ramzan ali Feb 02 '17 at 18:13
0

Are you sure this is how you want to display your image even if the solution works for you or are you open to other implementations?

Usually its best not to store images and binary data in the database (for performance and cost reasons), and you also don't want to embed the image binary data on the page as you are doing as this will increase the page load time and you won't be able to use a lot of the built-in features for optimization out of the box (IIS caching, browser caching, compression...)

A better approach might be to store the image on disk and the path in the database, the in your code build an HTML img element using the "src" property with the path as a URL.

Even if you still need to keep the image in the database, you might be better off saving the binary data to disk and serving it from there instead of embedding the bytes array.

I can provide you more information if you want to peruse this option.

------- Update Feb-03-17 -------

In your view, you want to build the HTML image with a link to the stored image, regardless of it being stored in the database or on disk by either using a link to a controller action such as:

<img src='@Url.Action("GetProfileImage", "User", new { Model.UserName })'/>

or by a link in your ViewModel such as:

<img src= "@Url.Content(Model.ImagePath)" alt="Image" />

As for storing the image path in your database, there are many ways. A simple implementation for storing the images in a directory within your site could look like the accepted answer in this post:

public ActionResult FileUpload(HttpPostedFileBase file)
{

    if (file != null)
    {
        Database1Entities db = new Database1Entities();
        string ImageName = System.IO.Path.GetFileName(file.FileName);
        string physicalPath =Server.MapPath("~/images/"+ ImageName);

        // save image in folder
        file.SaveAs(physicalPath);

        //save new record in database
        tblA newRecord = new tblA();
        newRecord.fname = Request.Form["fname"];
        newRecord.lname = Request.Form["lname"];
        newRecord.imageUrl = ImageName;
        db.tblAs.Add(newRecord);
        db.SaveChanges();

    }
    //Display records
    return RedirectToAction("../home/Display/");
}

For the display my recommendation would be to implement a controller that retrieve the image path from the database and returns a link, as in this post:

public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.
    return base.File(path, "image/jpeg");
}
Community
  • 1
  • 1
zaid safadi
  • 709
  • 7
  • 14
  • I will be glad if you provide such kind of informations. Thank's in advance. – ramzan ali Feb 03 '17 at 04:02
  • @ramzanali I've updated my answer with some code samples you can use to build the solution and links to other stackoverflow questions that want to do a similar thing. If this answer helped solve your problem please mark as an accepted answer. – zaid safadi Feb 04 '17 at 01:02