Working with Images

José Couto

New member
Joined
Nov 14, 2024
Messages
3
Programming Experience
Beginner
I'm a beginner. How do I program in C#, request an image for a pictureBox, update it and include it in the SQL SERVER Database, having a Photo Column of type image.
 
I think you first need to learn how to program in C# first.

Then you learn how to do GUI programming using C#. You seem to be leaning towards using WinForms. Personally, WinForms should only be used for maintaining legacy projects, not for greenfield projects.

Then you learn SQL. Better to do this straight up without any C# or ADO.NET first. Just use SSMS directly.

Then you learn how to access databases using C# using ADO.NET. (An alternative is Entity Framework which many will recommend, but I can't personally recommend.)

And then you learn how to put all of that together into your program that is your goal.

Any other approach (including asking ChatGPT, CoPilot, or Gemini to write the code for you) will be spoon-feeding and not lead to any deep learning if you are a beginner. If you have experience with other programming languages including SQL, and are already familiar with databases and GUI programming, then this might be a viable shortcut.
 
Last edited:
I have to agree with @Skydiver in general, but I will provide some specific information regarding the task at hand. Firstly, don't use the image data type in SQL Server. That has been deprecated for well over a decade. Use the varbinary data type. You will be working with byte arrays when moving data between your app and the database, so you need to convert between that and a .NET Image object.
Retrieve Image:
SqlConnection connection = new SqlConnection("connection string here");
SqlCommand command = new SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection);
 
connection.Open();
 
byte[] pictureData = (byte[])command.ExecuteScalar();
 
connection.Close();
 
Image picture = null;
 
// Create a stream in memory containing the bytes that comprise the image.
using (MemoryStream stream = new MemoryStream(pictureData))
{
    // Read the stream and create an Image object from the data.
    picture = Image.FromStream(stream);
}
Save Image:
SqlConnection connection = new SqlConnection("connection string here");
SqlCommand command = new SqlCommand("UPDATE MyTable SET Picture = @Picture WHERE ID = 1", connection);
 
// Create an Image object.
using (Image picture = Image.FromFile("file path here"))
{
    // Create an empty stream in memory.
    using (MemoryStream stream = new MemoryStream())
    {
        // Fill the stream with the binary data from the Image.
        picture.Save(stream, ImageFormat.Jpeg);
 
        // Get an array of Bytes from the stream and assign to the parameter.
        command.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = stream.GetBuffer();
    }
}
 
connection.Open();
command.ExecuteNonQuery();
connection.Close();
 
Back
Top Bottom