繁体   English   中英

使用varbinary(max)的SQL Server中的默认配置文件图片

[英]Default profile picture in sql server using varbinary(max)

我有一个带有用户个人资料页面的Web应用程序。 该页面允许用户上传自己的个人资料图片。 我正在寻找一种为数据库(SQL Server 2008)中的个人资料图片设置默认varbinary(max)值的方法。 注册后,Facebook之类的东西就会带有默认的个人资料照片。 我可以将图片上传到数据库并显示出来,但是如果数据库中的个人资料图片NULL ,则解码图像时会出错。

上传图片代码:

string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);

string contenttype = String.Empty;

switch (ext)
{
    case ".jpg":
       contenttype = "image/jpg";
       break;
}

if (contenttype != String.Empty)
{
   System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

   System.Drawing.Image newImage = new Bitmap(1024, 768);

   using (Graphics g = Graphics.FromImage(newImage))
   {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(uploaded, 0, 0, 1024, 768);
   }

   byte[] results;

   using (MemoryStream ms = new MemoryStream())
   {
         ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
         EncoderParameters jpegParms = new EncoderParameters(1);
         jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
         newImage.Save(ms, codec, jpegParms);
         results = ms.ToArray();
   }

显示图像代码:

string strQuery = "select profilepic from MemberAccount where nric='"+ Session["nric"] +"'";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
if (!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))
{
   download(dt);
}

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
       con.Open();
       sda.SelectCommand = cmd;
       sda.Fill(dt);
       return dt;
    }
    catch
    {
       return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}


private void download(DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(bytes);
    Response.End();
}

显示图像但出现错误时在部分中添加了if语句

if (!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))

这行给出错误:

Object reference not set to an instance of an object.

为什么不将默认图像保存在站点上的某些图像文件夹中? 这样,您不必读取数据库列,而使用图像控件中的相对路径。

尝试比较

if(!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM