.Net, ADO.NET, ASP.NET, C#, Database, Example Connection, Programming, SQL, Web Development, WebForms

C# Example Code to Save and Resize Images from your Database to a System Folder

In this example I will show how to use C# in a WebForm to read out a series of pictures from a database table, resize the pictures to a standardized width, and then to save each image as a JPEG to a folder on your local file system. The code assumes that the pictures are coming from your database as JPEG format images, but you can easily adjust the code to dynamically save each image by its type if you have this data stored in your database.

Step-by-Step Code Walkthrough

To start, we set up a SQL connection to the database, and then loop through the results using a DataReader. Each image from the SQL Server database is read out of the database as a byte array, which is then converted to an Image object so that we can better manipulate it in code:

imagedata = (byte[])reader[0];
System.Drawing.Image tmpOriginalImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(imagedata));

Once we have the original image from the database, we want to standardize the width. In this example we will standardize each variable-sized image to 140 pixels wide. This naturally also involves adjusting the height of each image by the same aspect ratio. The scale of adjustment is calculated as:

double dblScaleImg = (double)intDesiredWidth / (double)tmpOriginalImage.Width;

Now that we have the scale, we will set up an empty BitMap image container with the correct dimensions for the image that we want to create and save:

Graphics tmpGraphics = default(Graphics);
 Bitmap tmpResizedImage = new Bitmap(Convert.ToInt32(dblScaleImg * tmpOriginalImage.Width), Convert.ToInt32(dblScaleImg * tmpOriginalImage.Height));
 tmpGraphics = Graphics.FromImage(tmpResizedImage);

So far so good! But now comes the most important part; resizing the original image into our new image container with minimal distortion. To do so we can set a number of different image scaling options that are described in detail in this article on MSDN. In our code example we will use the HighQualityBilinear scaling option, which is appropriate for handling images that are scaled or rotated:

tmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

Now that our graphics object is properly set up, and our scaling dimensions are ready to be calculated, we set the original Image from our database into our new graphics object:

 tmpGraphics.DrawImage(tmpOriginalImage, 0, 0, tmpResizedImage.Width + 1, tmpResizedImage.Height + 1);

That completes our task of creating a new, standard-sized image from our original database object. The final step is to save our new image to our file system:

 System.Drawing.Image imageOut = tmpResizedImage;
 imageOut.Save("C:\\PicturesFolder\\testImage" + counter + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

As you can see, once you are familiar with the concepts and libraries, manipulating images in C# is quite straightforward. Have a look below at a fully functioning example of the concepts we just stepped through.

The Example Code

Here is a functional example of a simple ASP.NET WebForm with a button control on it. When the user clicks the button, a method is called which contains the script to save images from a database table to a folder on the local file system. As I mentioned, the process also involves resizing each image to a standardized width and corresponding height based on the image’s original aspect ratio.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Data.SqlClient" %>
<%@ Import Namespace = "System.IO" %>
<%@ Import Namespace = "System.Drawing" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 protected void Button1_Click(object sender, EventArgs e)
 {
 string strConn = "uid=MyUserId;pwd=MyPassword;server=MyPictureServer;database=MyDatabaseName;Connect Timeout=600";
 SqlConnection conn = null;
 SqlCommand cmd = null;
 Int32 counter = 0;
 byte[] imagedata = null;
 Int32 intDesiredWidth = 140;

 try
 {
 conn = new SqlConnection(strConn);
 cmd = new SqlCommand();
 cmd.Connection = conn;
 cmd.CommandText = "SELECT MyPictures FROM MyDatabaseTable WHERE SomeConditions=True";
 cmd.CommandTimeout = 30;
 cmd.CommandType = CommandType.Text;
 conn.Open();
 SqlDataReader reader = cmd.ExecuteReader();
 if (reader.HasRows)
 {
 while (reader.Read())
 {
 imagedata = (byte[])reader[0];
 System.Drawing.Image tmpOriginalImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(imagedata));
 double dblScaleImg = (double)intDesiredWidth / (double)tmpOriginalImage.Width;
 Graphics tmpGraphics = default(Graphics);
 Bitmap tmpResizedImage = new Bitmap(Convert.ToInt32(dblScaleImg * tmpOriginalImage.Width), Convert.ToInt32(dblScaleImg * tmpOriginalImage.Height));
 tmpGraphics = Graphics.FromImage(tmpResizedImage);
 tmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
 tmpGraphics.DrawImage(tmpOriginalImage, 0, 0, tmpResizedImage.Width + 1, tmpResizedImage.Height + 1);
 System.Drawing.Image imageOut = tmpResizedImage;
 imageOut.Save("C:\\PicturesFolder\\testImage" + counter + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
 counter++;
 }
 }
 reader.Close();
 }
 catch (Exception ex)
 {
 }
 finally
 {
 if (cmd != null) cmd.Dispose();
 if (conn != null)
 {
 conn.Close();
 conn.Dispose();
 }
 }
 }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
 </div>
 </form>
</body>
</html>
Advertisements

4 thoughts on “C# Example Code to Save and Resize Images from your Database to a System Folder”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s