Thursday, 9 August 2012

.Net Code to Resize images in Directory

The below code help to resize the images within a directories. The code is more self explanatory. I have googled and nothing workout for me. Most of the code in the google are working partially and available in bits and pieces. So I've integrated them and made it work in a fine manner.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;


public class ImageResizer
{
    const string srcpath = "P:\\";
    const string destpath = "N:\\";
    static void Main()
    {
        Console.WriteLine("Processing Image...........");
        int filecount;
        filecount = 1;

        MyImageProcessingClass myobject = new MyImageProcessingClass();
        myobject.ProcessFiles(srcpath, destpath, 1);

        Console.WriteLine("Image Resized Successfully...........");
        Console.Read();
        Console.ReadLine();
    }
}
public class MyImageProcessingClass
{

    public bool CheckJpgFile(string filename)
    {     // add other possible extensions here  
        return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
        || Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase);
    }

    public void ProcessFiles(string path, string destpath, int filecount)
    {
        string[] files;
        string[] directories;

        string filename;
        files = Directory.GetFiles(path);


        foreach (string file in files)
        {

            // Process each file                    
            bool isJpeg = CheckJpgFile(file);
            Console.WriteLine(isJpeg);
            if (isJpeg == true)
            {
                Image img = Resize(Image.FromFile(file));
                filename = destpath + Convert.ToString(filecount) + ".jpg";
                filecount = filecount + 1;
                SaveJPGWithCompressionSetting(img, filename, 80L);
            }
        }

        directories = Directory.GetDirectories(path);
        foreach (string directory in directories)
        {
            // Process each directory recursively
            ProcessFiles(directory, destpath, filecount);
        }
    }

    /// <summary>
    /// method for resizing an image
    /// </summary>
    /// <param name="img">the image to resize</param>
    /// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param>
    /// <returns></returns>
    public Image Resize(Image img)
    {
        //get the height and width of the image
        int originalW = img.Width;
        int originalH = img.Height;

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

        //get the new size based on the percentage change
        int resizedW = 196;
        int resizedH = 228;

        if (img.Width <= resizedW)
        {
            resizedW = img.Width;
        }

        resizedH = img.Height * resizedW / img.Width;
        if (resizedH > originalH)
        {
            // Resize with height instead
            resizedW = img.Width * originalH / img.Height;
            resizedH = originalH;
        }

        System.Drawing.Image NewImage = img.GetThumbnailImage(resizedW, resizedH, null, IntPtr.Zero);


        //create a new Bitmap the size of the new image
        Bitmap bmp = new Bitmap(resizedW, resizedH);
        //create a new graphic from the Bitmap
        Graphics graphic = Graphics.FromImage((Image)bmp);

        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.InterpolationMode = InterpolationMode.NearestNeighbor;
        graphic.PixelOffsetMode = PixelOffsetMode.Half;

        //draw the newly resized image

        graphic.DrawImage(NewImage, 0, 0, resizedW, resizedH);

        //dispose and free up the resources
        graphic.Dispose();
        //return the image
        return (Image)bmp;
    }


    public ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }

    public void SaveJPGWithCompressionSetting(Image image, string szFileName, long lCompression)
    {
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, lCompression);
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
        image.Save(szFileName, ici, eps);
    }

}



No comments:

Post a Comment