I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast ‘OriginalPhoto’ or ‘Thumbnail’ an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don’t understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error ‘Unable to display the given data’. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?
PROFILEGALLERY TABLE CONTAINS:
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(); }
You should use sql parameters: