我以前做过,但方式不同。我试图让下面的代码工作。如果我不投射“OriginalPhoto”或“Thumbnail”,则会发生错误。不允许从数据类型 varchar 到 varbinary(max) 的隐式转换。使用 CONVERT 函数运行此查询。我不明白为什么它要求演员。但是,如果我确实投射它,图像以二进制数据格式添加到数据库中就好了。尝试查看图像时,我收到错误“无法显示给定数据”。我已经使用 SqlDataAdapter 将两个 byte[] 插入到表中,并且可以正常工作。我想使用这种方法,但我做错了什么?
ProfileGALLERY 表包含:
UserId nvarchar(50)
Title nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)
protected void AddPhotoToDatabase()
{
byte[] OriginalPhoto = GetImage();
byte[] Thumbnail = GenerateThumbnail();
string Title = FileUpload1.FileName.ToString();
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
protected byte[] GetImage()
{
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
return photo;
}
protected byte[] GenerateThumbnail()
{
System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
double thumbwidth = 0;
double thumbheight = 0;
double imgsz = 150.0;
if (imgsz / image.Width < imgsz / image.Height)
{
thumbwidth = image.Width * (imgsz / image.Width);
thumbheight = image.Height * (imgsz / image.Width);
}
else
{
thumbwidth = image.Width * (imgsz / image.Height);
thumbheight = image.Height * (imgsz / image.Height);
}
System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}