Click here to Skip to main content
13,350,029 members (49,092 online)
Click here to Skip to main content
Add your own
alternative version


51 bookmarked
Posted 15 Sep 2008

Image manipulation and reading and writing to a database

, 7 Oct 2008
Rate this:
Please Sign up or sign in to vote.
This code allows you to read/write from a database and change image dimensions, size, and quality.


There are so many articles available which show you how to insert a picture to a database and read it back, how to reduce the quality and size, and how to change the dimensions. I haven’t come across any article which does all the above in one project. This article will show you all these tricks, like, change the quality of photo so the size can be smaller without compromising the quality [for web publishing or email purposes], change the dimension, how to save pictures to a database, and how to read images from a database and then display in an image control. This is ideal for bulk processing.


The basic idea is taken from an article in GeekPedia by Andrei Pociu; some help was taken from Microsoft and the DZone Snippets website.

Using the code

The code below will load a the list from your folder which contains pictures:

if (fbdOpen.ShowDialog() == DialogResult.OK)
    // Clear any previous items in the list
    // Run a loop through all the files in the directory at the selected path
    foreach (string Filename in Directory.GetFiles(fbdOpen.SelectedPath))
        // We'll create a new FileInfo object from the file path
        FileInfo fiPicture = new FileInfo(Filename);
        // If it's a JPEG file
        if (fiPicture.Extension.ToLower() == ".jpeg" || 
            fiPicture.Extension.ToLower() == ".jpg")
            // Add it to the list of files
// We want the ProgressBar to have the same
// maximum value as the number of pictures to resize
prgReduce.Maximum = lstPhotos.Items.Count;

This will process your request to resize, adjust quality, and save to a database, as well as save to another folder with the desired size and quality.

// Reset the progress bar
prgReduce.Value = 0;
// Show the FolderBrowserDialog where
// the user selects where to save the files
if (fbdSave.ShowDialog() == DialogResult.OK)
    // We will store the correct image codec in this object
    ImageCodecInfo iciJpegCodec = null;
    // This will specify the image quality to the encoder
    EncoderParameter epQuality = 
      new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 
    // Get all image codecs that are available
    ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders();
    // Store the quality parameter in the list of encoder parameters
    EncoderParameters epParameters = new EncoderParameters(1);
    epParameters.Param[0] = epQuality;

    // Loop through all the image codecs
    for (int i = 0; i < iciCodecs.Length; i++)
        // Until the one that we are interested
        // in is found, which is image/jpeg
        if (iciCodecs[i].MimeType == "image/jpeg")
            iciJpegCodec = iciCodecs[i];

    // Loop through the files in the list
    // Insert to database and Save on Disk
    foreach (string strFile in lstPhotos.Items)
        SqlConnection cn = new SqlConnection(strCn);
        SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest" + 
                         " (BLOBData, BLOBName, InsertDate) " + 
                         "VALUES (@BLOBData, @BLOBName, @DateTime)", cn);

        // Take another step on the progress bar

        // Create a new Image object from the current file
        Image newImage = Image.FromFile(strFile);


        // Get the file information again,
        // this time we want to find out the extension
        FileInfo fiPicture = new FileInfo(strFile);

        //Get the desired photos size
        int PhotoWidth = 0;
        if (radioButton1.Checked)
            PhotoWidth = 1024;
        else if(radioButton2.Checked)
            PhotoWidth = 640;
        else if (radioButton3.Checked)
            PhotoWidth = 420;

        //Re-Size the photo
        System.Drawing.Image ImageReSized = 
                 ResizeImage(strFile, fbdSave.SelectedPath.ToString() + 
                 "\\" + fiPicture.Name, PhotoWidth, 768, false);
                 //newImage.GetThumbnailImage(640, 480, null, IntPtr.Zero);

        //Convert Image to byt to save on database
        System.Drawing.ImageConverter ic =
           new System.Drawing.ImageConverter();
        byte[] bytBLOBData = new byte[1];
        bytBLOBData = (byte[])ic.ConvertTo(ImageReSized, bytBLOBData.GetType());
        //Update the database
        SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, 
                           bytBLOBData.Length, ParameterDirection.Input, false, 
                           0, 0, null, DataRowVersion.Current, bytBLOBData);
        SqlParameter prm1 = new SqlParameter("@BLOBName", SqlDbType.VarChar, 100, 
                            ParameterDirection.Input, false, 0, 0, null, 
                            DataRowVersion.Current, fiPicture.FullName);
        SqlParameter prm2 = new SqlParameter("@DateTime", SqlDbType.DateTime, 21, 
                            ParameterDirection.Input, false, 0, 0, null, 
                            DataRowVersion.Current, DateTime.Now);

        //Add parameter 


        // Save resized picture here 
        ImageReSized.Save(fbdSave.SelectedPath.ToString() + "\\" + 
                          fiPicture.Name, iciJpegCodec, epParameters);
    // Open the folder containing the new items

The code above calls this function to change the dimensions:

System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(originalFile);

// Prevent using images internal thumbnail

if (onlyResizeIfWider)
    if (FullsizeImage.Width <= newWidth)
        newWidth = FullsizeImage.Width;

int NewHeight = FullsizeImage.Height * newWidth / FullsizeImage.Width;
// NewHeight = maxHeight; //temp Test
if (NewHeight > maxHeight)
    // Resize with height instead
    newWidth = FullsizeImage.Width * maxHeight / FullsizeImage.Height;
    NewHeight = maxHeight;

System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(newWidth, 
                                NewHeight, null, IntPtr.Zero);

// Clear handle to original file so that we can overwrite it if necessary

// Save resized picture here as well if you wish to
// NewImage.Save(newFile);
return NewImage;

Points of interest

Now, you have all the code in one project which allows you to manipulate your images or photos. Now, my wife does not have to use PaintBrush to reduce picture quality to sent a photo by email.


This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


About the Author

aqueel [aqeel] Syed
Team Leader Ultimate Business solution
Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionWhere's the source files? Pin
andwan07-Jun-09 8:08
memberandwan07-Jun-09 8:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 8 Oct 2008
Article Copyright 2008 by aqueel [aqeel] Syed
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid