Click here to Skip to main content
15,884,629 members
Articles / Web Development / ASP.NET
Article

Image manipulation and reading and writing to a database

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
7 Oct 2008CDDL1 min read 32.6K   638   51   1
This code allows you to read/write from a database and change image dimensions, size, and quality.

Introduction

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.

Background

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:

C#
if (fbdOpen.ShowDialog() == DialogResult.OK)
{
    // Clear any previous items in the list
    lstPhotos.Items.Clear();
    // 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
            lstPhotos.Items.Add(Filename);
        }
    }
}
// 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.

C#
// 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, 
                          (int)numQual.Value);
    // 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];
            break;
        }
    }

    // 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
        prgReduce.PerformStep();

        // 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 
        cmd.Parameters.Add(prm);
        cmd.Parameters.Add(prm1);
        cmd.Parameters.Add(prm2);
                    
        cn.Open();
        cmd.ExecuteNonQuery();

        cn.Close();

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

The code above calls this function to change the dimensions:

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

// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

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
FullsizeImage.Dispose();

// 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.

License

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


Written By
Team Leader Ultimate Business solution
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhere's the source files? Pin
andwan07-Jun-09 7:08
andwan07-Jun-09 7: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.