Click here to Skip to main content
12,634,403 members (25,606 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

73K views
12K downloads
79 bookmarked
Posted

Simple Image Editor with Crop and Resize while Maintaining Aspect Ratio

, 30 Dec 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
An amalgamation of CodeProject ideas
CropResizeSrc

Introduction

I was developing a project that required adding images to a database. Most of the images were acquired from an 8 megapixel digital camera, so the sizes were quite large.  I originally just re-sized the images proportionally to 1024 x 768 and called it good.  But it bothered me that some images contained busy backgrounds or distractions that could be cropped out. This project is the result of my efforts. 

Background 

Note that I don't claim to have written most of the code for this project. I have stood on the shoulders of giants, and learned and reused code from many different CodeProject articles.  Hopefully, the whole is greater than the sum of its parts. This article is based upon code from ImageResizer.aspx and various CodeProject articles.

Using the Code 

The source code should be fairly self explanatory.

The secret is keeping all of the aspect ratios correct.

private static Image CropImage(Image img, Rectangle cropArea)
{
    try {
	Bitmap bmpImage = new Bitmap(img);
	Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
	return (Image)(bmpCrop);
    }
    catch (Exception ex)
    {
	MessageBox.Show(ex.Message, "CropImage()");
    }
    return null;
}

private void saveJpeg(string path, Bitmap img, long quality)
{
    // Encoder parameter for image quality
    EncoderParameter qualityParam = new EncoderParameter(
    System.Drawing.Imaging.Encoder.Quality, (long)quality);

    // Jpeg image codec
    ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg");

    if (jpegCodec == null)
    {
	MessageBox.Show("Can't find JPEG encoder?", "saveJpeg()");
	return;
    }
    EncoderParameters encoderParams = new EncoderParameters(1);
    encoderParams.Param[0] = qualityParam;
  
    img.Save(path, jpegCodec, encoderParams);
}

private ImageCodecInfo getEncoderInfo(string mimeType)
{
    // Get image codecs for all image formats
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

    // Find the correct image codec
    for (int i = 0; i < codecs.Length; i++)
	if (codecs[i].MimeType == mimeType)
   	   return codecs[i];

    return null;
}

private void btnOK_Click(object sender, EventArgs e)
{
    // output image size is based upon the visible crop rectangle and scaled to 
    // the ratio of actual image size to displayed image size
    Bitmap bmp = null;

    Rectangle ScaledCropRect = new Rectangle();
    ScaledCropRect.X         = (int)(CropRect.X / ZoomedRatio);
    ScaledCropRect.Y         = (int)(CropRect.Y / ZoomedRatio);
    ScaledCropRect.Width     = (int)((double)(CropRect.Width) / ZoomedRatio);
    ScaledCropRect.Height    = (int)((double)(CropRect.Height) / ZoomedRatio);

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
	try
	{
       bmp = (Bitmap)CropImage(pictureBox1.Image, ScaledCropRect);
	   // 85% quality
	   saveJpeg(saveFileDialog1.FileName, bmp, 85);
	}
	catch(Exception ex)
	{
	   MessageBox.Show(ex.Message, "btnOK_Click()");
	}
    }

    if(bmp != null)
         bmp.Dispose();
}

Points of Interest 

There is a transparent crop box that may be dragged by its corners, or moved by left clicking and moving. The aspect ratio of the crop box is determined by the value in the combo box.   The other combo box simply sets the width of the crop box, and the height is determined by the chosen aspect ratio.  The crop box will snap to a proportional aspect ratio when re-sized.

There are some simple image processing features available; rotate, invert color, gray scale, contrast and brightness. 

NOTE: All of my images are landscape, so I have not spent any time on portrait mode resizing conditions in the code.

History

  • 28th December, 2008: Initial release
  • 30th December, 2008: Updated with corrected code

License

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

Share

About the Author

Member 3647417
United States United States
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
GeneralChange of contrast doesn't work Pin
RenniePet16-Apr-13 15:27
memberRenniePet16-Apr-13 15:27 
QuestionHow to resize Image Pin
Member 793228411-Oct-12 21:26
memberMember 793228411-Oct-12 21:26 
GeneralMy vote of 5 Pin
The nk6-Oct-11 22:07
memberThe nk6-Oct-11 22:07 
GeneralMy vote of 5 Pin
asaab20-Oct-10 5:06
memberasaab20-Oct-10 5:06 
Generalset background color Pin
Babita Shivade15-Apr-09 2:52
memberBabita Shivade15-Apr-09 2:52 
Questionhow we can crop small image Pin
Babita Shivade14-Apr-09 20:39
memberBabita Shivade14-Apr-09 20:39 
GeneralFIND ERROR AND SOLUTION Pin
~Dim~8-Apr-09 1:45
member~Dim~8-Apr-09 1:45 
GeneralRe: FIND ERROR AND SOLUTION Pin
Stephan.Zeller23-Jun-09 23:27
memberStephan.Zeller23-Jun-09 23:27 
Generalno mercy Pin
kreont12-Jan-09 7:44
memberkreont12-Jan-09 7:44 
GeneralNote! Pin
Member 364741729-Dec-08 7:36
memberMember 364741729-Dec-08 7:36 
GeneralRe: Note! Pin
Member 364741730-Dec-08 6:54
memberMember 364741730-Dec-08 6:54 
QuestionRe: Note! Pin
stixoffire10-Jan-09 12:22
memberstixoffire10-Jan-09 12:22 
AnswerRe: Note! - My benefit from this article :) Pin
LastZolex19-Apr-10 1:52
memberLastZolex19-Apr-10 1:52 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 30 Dec 2008
Article Copyright 2008 by Member 3647417
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid