Click here to Skip to main content
15,889,281 members
Articles / Programming Languages / C#
Tip/Trick

Image Re-sizing Utility

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Apr 2013CPOL2 min read 10.1K   353   9  
Re-sizing images to equalize the width & height

Introduction

Often you come across a problem wherein you need to view/ showcase product's using its images on websites like e-commerce, shopping cart etc.. and you have images with different width and height. And client wants these products to be showcased very neatly so they look aligned on the website without loosing the original resolution. This image re-sizing tool does exactly the same. It re-sizes the images with different width & height and also creates a thumbnail copy of the same maintaining the aspect ratio. (You may specify the size of thumbnail version of image.)

Background 

One of my friend from client side requested me, if I can create a tool which can equalize the width & height of lot of images at once, if all of these images are dumped in a single directory.  When he mentioned he has to use some sort of paint software to re-size the images manually, I felt very sorry for him and I promised him that I would make an utility, which will make his job simpler. Hope this would be helpful for others as well.

Here is how you can use this utility. Click on "Browse & Resize" button to select the folder/ directory which contains the images to be re-sized. As soon as you select the directory, utility will start resizing the images and dump it under the same directory with "/images/" sub-directory. Before selecting the directory don't forget to specify the thumbnail image size. As you can see by default the 100 px of size is specified. The thumbnails will be created under "/images/thumb/" directory.

 I've added image preview and a progress bar blocks to give an interactive look to the utility.  

Using the code  

It has been long time since I developed this utility. So please forgive me, if I could not explain it very well. Although, I will try my level best to pin-point major parts of source code.  

C#
// Image Re-sizing function
        public bool ImageResizing(string WorkingDirectory, int thumbSize, PictureBox pb1, ProgressBar progressBar1)
        {
            try
            {
                ArrayList list = new ArrayList();
                DirectoryInfo info = new DirectoryInfo(WorkingDirectory);
                Char cImgFormat = 'J';

                foreach (FileInfo info2 in info.GetFiles())
                {
                    if ((info2.Extension == ".jpg") || (info2.Extension == ".jpeg"))
                    {
                        list.Add(info2.Name);
                        cImgFormat = 'J';
                    }
                    else if (info2.Extension.ToLower() == ".bmp")
                    {
                        list.Add(info2.Name);
                        cImgFormat = 'B';
                    }
                    else if (info2.Extension.ToLower() == ".gif")
                    {
                        list.Add(info2.Name);
                        cImgFormat = 'G';
                    }
                    else if(info2.Extension.ToLower()  == ".png")
                    {
                        list.Add(info2.Name);
                        cImgFormat = 'P';
                    }
                }

                progressBar1.Minimum = 1;
                progressBar1.Maximum = list.Count;
                progressBar1.Value = 1;
                progressBar1.Style = ProgressBarStyle.Continuous;
                progressBar1.Step = 1;

                foreach (string str in list)
                {
                    Image imgPhoto = Image.FromFile(WorkingDirectory + @"\" + str);
                    Image image2 = null;
                    Image image3 = null;
                    int width = 0;
                    int height = 0;
                    width = imgPhoto.Width;
                    height = imgPhoto.Height;
                    if (height > width)
                    {
                        width = height;
                    }
                    else
                    {
                        height = width;
                    }
                    image2 = FixedSize(imgPhoto, width, height);
                    if (!Directory.Exists(WorkingDirectory + @"\images"))
                    {
                        Directory.CreateDirectory(WorkingDirectory + @"\images");
                    }
                    if (!Directory.Exists(WorkingDirectory + @"\images\thumb"))
                    {
                        Directory.CreateDirectory(WorkingDirectory + @"\images\thumb");
                    }

                    pb1.Refresh();
                    image3 = FixedSize(image2, thumbSize, thumbSize);
                    Bitmap resizedImage = new Bitmap(image3);
                    Graphics gfx = Graphics.FromImage(resizedImage);
                    gfx.DrawImage(resizedImage, 0, 0, image3.Width, image3.Height);

                    if (cImgFormat == 'J')
                    {

                        pb1.Image = resizedImage;
                        image2.Save(WorkingDirectory + @"\images\" + str, ImageFormat.Jpeg);
                        image3.Save(WorkingDirectory + @"\images\thumb\" + str, ImageFormat.Jpeg);
                    }
                    else if (cImgFormat == 'B')
                    {
                        pb1.Image = resizedImage;
                        image2.Save(WorkingDirectory + @"\images\" + str, ImageFormat.Bmp);
                        image3.Save(WorkingDirectory + @"\images\thumb\" + str, ImageFormat.Bmp);
                    }
                    else if (cImgFormat == 'G')
                    {
                        pb1.Image = resizedImage;
                        image2.Save(WorkingDirectory + @"\images\" + str, ImageFormat.Gif);
                        image3.Save(WorkingDirectory + @"\images\thumb\" + str, ImageFormat.Gif);
                    }
                    else if (cImgFormat == 'P')
                    {
                        pb1.Image = resizedImage;
                        image2.Save(WorkingDirectory + @"\images\" + str, ImageFormat.Png);
                        image3.Save(WorkingDirectory + @"\images\thumb\" + str, ImageFormat.Png);
                    }
                    System.Threading.Thread.Sleep(500);
                    progressBar1.PerformStep();
                    image2.Dispose();
                    image3.Dispose();
                }
                return true;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                return false;
            }
        }

 

As you will notice, this utility supports the images of type JPG/ JPEG, BMP, GIF and PNG file formats. Later the for loop loops through the images in specified directory, picking them one by one and passing the image parameters to a sub-function "FixedSize()" as shown below. 

C#
private static Image FixedSize(Image imgPhoto, int Width, int Height)
        {
            int width = imgPhoto.Width;
            int height = imgPhoto.Height;
            int x = 0;
            int y = 0;
            int num5 = 0;
            int num6 = 0;
            float num7 = 0f;
            float num8 = 0f;
            float num9 = 0f;
            num8 = ((float) Width) / ((float) width);
            num9 = ((float) Height) / ((float) height);
            if (num9 < num8)
            {
                num7 = num9;
                num5 = (int) ((Width - (width * num7)) / 2f);
            }
            else
            {
                num7 = num8;
                num6 = (int) ((Height - (height * num7)) / 2f);
            }
            int num10 = (int) (width * num7);
            int num11 = (int) (height * num7);
            Bitmap image = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            image.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Clear(Color.White);
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(imgPhoto, new Rectangle(num5, num6, num10, num11), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
            graphics.Dispose();
            return image;
        }  

 

SetResolution() function of Bitmap class plays an important role in maintaining the aspect ratio of the image before it gets re-sized.  

I'm sure there might be better ways to accomplish the re-sizing of images. Please feel free to share or suggest the better alternatives. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --