Skip to content
Advertisement

Can’t convert SQL VARBINARY to byte[] correctly and convert to Image in ASP.NET c#

Here is what I’m doing:

public static MVC_Picture GetPictureRecord(int pictureID)
{
    int pictureId = pictureID;
    MVC_Picture _picture = new MVC_Picture(); //object that stores name and array

    var connString = db.connString;
    string cmdText = "SELECT PictureName, PictureImage FROM Picture WHERE CONVERT(INT, ID) =@pictureId;";
    using (var connection = new SqlConnection(connString))
    {
        using (var sqlCmd = new SqlCommand(cmdText, connection))
        {
            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@pictureId";
            param1.Value = pictureId;
            sqlCmd.Parameters.Add(param1);

            connection.Open();
            SqlDataReader dr = sqlCmd.ExecuteReader();
            while (dr.Read())
            {
                _picture.Id = pictureId;
                _picture.PictureName = Convert.ToString(dr["PictureName"]);
                _picture.PictureImage = (byte[])(dr["PictureImage"]); //Problem
            }
            connection.Close();
        }
    }

    return _picture; 
}

When I convert to byte[] I get something like: {byte[4354567]}

I’m then trying to convert array to Image like so:

Image img = (Image)converter.ConvertFrom(_picture.PictureImage);
ViewModel.FeaturedImage = img;

And in View I use:

<img src="@ViewModel.FeaturedImage" alt="Featured Image" />

What am I missing?

Advertisement

Answer

<img src=… has to point to an image file by its path, eg <img src="/myImage.jpg">. You can’t stick a binary representation of the image in the src and have it work.

So you could either write those binary images out to disk somewhere (you probably don’t want to do that, as then you’re duplicating the data, and would have to manage synchronizing).

Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.

This is an MVC controller action that I’ve used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:

<img src="Competition/ViewJobDescription?competitionId=1234" />

    public ActionResult ViewJobDescription(int competitionId)
    {
        string errorMsg = "";
        var competition = new DBModel.Competition();
        try
        {               
            competition = DBModel.Competition.GetCompetition(competitionId);
            if (competition != null && competition.AttachmentContent != null)
            {
                byte[] fileData = competition.AttachmentContent;
                string filename = competition.AttachmentTitle + ".pdf";
                return File(fileData, "application/pdf", filename);
            }
        }
        catch (Exception ex)
        {
            errorMsg += "An error occured: " + ex.Message;
            LogFile err = new LogFile();
            err.CreateErrorLog(errorMsg);

            ModelState.AddModelError(string.Empty, errorMsg);
        }

        return RedirectToAction("Index", "Home");
    }
Advertisement