我有一个具有用户个人资料页面的 Web 应用程序。该页面允许用户上传自己的个人资料图片。我正在寻找一种varbinary(max)
在数据库(SQL Server 2008)中为我的个人资料图片设置默认值的方法。像 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.