Resizing images retrieved from SQL server

This is a nice neat way of resizing an image, I've simplified it and de-refactored (?) it for simplicity. Firstly, you ask for your image from the database:

SqlCommand cmd = new SqlCommand( "SELECT image FROM images WHERE id=@id" , connection);
cmd.Parameters.Add( "@id" , Request.QueryString[ "id" ]);
SqlDataReader dr = cmd.ExecuteReader();

Allocate an array of bytes to store it in temporarily:

byte[] image = null;
while (dr.Read())
  image = (byte[])dr.GetValue(0);

Now you have an array of bytes that contains your image, you can freely load it into a bitmap from the array:

Bitmap b = (Bitmap)Bitmap.FromStream( new MemoryStream(image));

And you can resize that bitmap easily using the overloaded bitmap constructor:

Bitmap output = new Bitmap(b, new Size(320, 240);

One resized bitmap that you can now save or send anywhere - including Response.OutputStream!

You might also like...


Simon Soanes


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra