Click here to Skip to main content
6,305,776 members and growing! (17,966 online)
Email Password   helpLost your password?
Multimedia » General Graphics » General     Intermediate License: The Common Development and Distribution License (CDDL)

Image manipulation and reading and writing to a database

By aqueel [aqeel] Syed

This code allows you to read/write from a database and change image dimensions, size, and quality.
C# (C# 1.0, C# 2.0, C# 3.0), Windows (Win2K, WinXP, Win2003, Vista, TabletPC), .NET (.NET 3.0, .NET 3.5), ASP.NET, GDI+, Dev
Posted:15 Sep 2008
Updated:7 Oct 2008
Views:6,175
Bookmarked:37 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
3 votes for this article.
Popularity: 2.27 Rating: 4.75 out of 5

1

2

3
1 vote, 33.3%
4
2 votes, 66.7%
5

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:

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.

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

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)

About the Author

aqueel [aqeel] Syed


Member

Occupation: Team Leader
Company: Ultimate Business solution
Location: Australia Australia

Other popular General Graphics articles:

  • A flexible charting library for .NET
    Looking for a way to draw 2D line graphs with C#? Here's yet another charting class library with a high degree of configurability, that is also easy to use.
  • CxImage
    CxImage is a C++ class to load, save, display, transform BMP, JPEG, GIF, PNG, TIFF, MNG, ICO, PCX, TGA, WMF, WBMP, JBG, J2K images.
  • 3D Pie Chart
    A class library for drawing 3D pie charts.
  • Really cool visual FX
    A set of classes for doing stunning visual effects, including water, plasma and fire.
  • ImageStone
    An article on a library for image manipulation.
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralWhere's the source files? Pinmemberandwan08:08 7 Jun '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Oct 2008
Editor: Smitha Vijayan
Copyright 2008 by aqueel [aqeel] Syed
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project