Home > Uncategorized > Photo Resizer program - Csharp Tutorial

Photo Resizer program - Csharp Tutorial

February 17th, 2012

Basic Problem - Recent advent of high megapixel has created one problem - large image sizes. Today the Camera's come at 15 Megapixels and higher. There are few issues with large size pictures

1. It takes longer to upload to facebook because of the size.
2. It is impractical to send large size image using email.
3. Viewing large size creates issues when viewing it in some photo viewer.

When you transfer the photos from your camera to your computer, it gets stored in a directory. We wish to write a simple program that will create a new directory and will put all the resized images in the new directory.

Here is goes.

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace Tutorial
{
class ImageResize
{
enum Dimensions
{
Width,
Height
}

[STAThread]
static void Main(string[] args)
{
//set a working directory
string WorkingDirectory = @"C:\Users\abhinsv\Desktop\Imageresize_src";

string[] array1 = Directory.GetFiles(WorkingDirectory,"*.jpg");

Console.WriteLine("Enter the percentage you wish to compress");
int pc = Convert.ToInt32 (Console.ReadLine());

System.IO.Directory.CreateDirectory(WorkingDirectory + @"\images" + pc.ToString() + @"\");

foreach (string name in array1)

{

Image imgPhotoVert = Image.FromFile(name);
Image imgPhoto = null;

imgPhoto = ScaleByPercent(imgPhotoVert, pc);
imgPhoto.Save(WorkingDirectory + @"\images"+ pc.ToString()+ @"\" + Path.GetFileName(name), ImageFormat.Jpeg);
imgPhoto.Dispose();

}

}
static Image ScaleByPercent(Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}

}

}

If you are uninitiated, you may like to take CSharp Tutorial.

Uncategorized

  1. No comments yet.
  1. No trackbacks yet.