Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I'm trying to save image to SQL database but it gives me the error: A generic error occurred in GDI+. My purpose is that the user loads an image using OpenFileDialog and the image is set to an Image control. Then when the user clicks Update Profile, the image is saved to SQL field. When I try to save it from my PC, it works perfectly, but on the other PC it doesn't work.

First when the user chooses picture using OpenFileDialog, I set the path to a String variable, called imagePath. Then when trying to save the picture in database I use the following code:

C#
command.CommandText = "update users set avatar = @image where id = '" + user_id + "'"; // The ID of the current logged user

System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath); // Creating            image from the file chosen from OpenFileDialog
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
String str = Convert.ToBase64String(imageBytes);   // Converting the byte array to                String
ms.Close();
     command.Parameters.AddWithValue("@image", str);  // Saving the image as string to database


By the way when I catch the exception of the error, it points that there's an error with the function System.Drawing.Image.FromFile.

Anyway I checked the value of imagePath variable and I assured it was correct. As I said, it works on my PC, but not on the others. Do I need to send to others some file connected to GDI in order to work properly? Thanks in advance for any help!
Posted

1 solution

Don't save it as a string - save it in the database as an image type. That means you can save the byte array directly to SQL without converting it to a base64 string.

BTW, your description of the exception you're getting sucks (not to put to fine a point on it). Saying that you get "an error with the function" doesn't tell us ANYTHING.
 
Share this answer
 
Comments
George Findulov 27-Aug-11 13:50pm    
Here's the exact error. I hope you can understand what it means. Thanks!
http://store.picbg.net/pubpic/D7/35/319f8a025982d735.jpg

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900