无法将SQL VARBINARY正确转换为byte []并在ASP.NET c#中转换为Image

时间:2019-03-07 19:11:11

标签: c# sql arrays image-processing

这是我在做什么:

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; 
}

当我转换为byte[]时,会得到类似{byte[4354567]}

的信息:

然后,我试图像这样将数组转换为Image

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

在View中,我使用:

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

我想念什么?

1 个答案:

答案 0 :(得分:0)

<img src= ...必须通过其 path 指向图像文件,例如<img src="/myImage.jpg">。您无法将图像的二进制表示形式粘贴在src中并使其起作用。

因此,您可以将这些二进制映像写到磁盘中的某个位置(您可能不想这样做,因为那样您就在复制数据,并且必须管理同步)。

或者您可以创建某种图像处理程序,因此<img src=类似于:<img src="/myHandler/imageId",然后让处理程序从数据库中读取二进制数据并响应图像。 / p>

这是我过去使用过的MVC控制器操作,用于从数据库中读取二进制PDF,并将其作为文件返回。这是在我的Competition控制器中。如果返回的是图片,则可以将其命名为:

<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");
    }