473,396 Members | 1,853 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Cropping Images in C#

All:

I looked around and could not find a simple yet complete example of
cropping an image in C#. I had the problem of needing to shave off the
bottom-most 18 lines of a directory full of images. The following code
does this. I hope that this serves as a concise yet complete example
of how to tackle cropping an image.

---
Note that inputDireName and outputDirName have been set in the class
someplace else.

private static void CropImages()
{
// Get all the files from the source directory

DirectoryInfo di = new DirectoryInfo(inputDirName);
FileInfo[] imageFileNames = di.GetFiles();

// Process each file, one by one
foreach (FileInfo fi in imageFileNames) {

// If this is not an image file, skip it
if (!IsImageFile(fi.FullName)) {
continue;
}

// Take a piece of the orginal image and write it to
the
// cropped image.

Image imgOriginal; // Image read from disk
Bitmap imgCropped; // Image created from original
Rectangle rOriginal; // Source rectangle of
original
Rectangle rCropped; // Destination (cropped)
rectangle
Graphics g; // Graphics surface of
destination image
string outFileName; // Name of cropped image file
written out

try {
// Load the original image
imgOriginal = Image.FromFile(fi.FullName);

// Calculate the cropped image dimensions and
create a surface
// on which to draw it
imgCropped = new Bitmap(imgOriginal.Width,
imgOriginal.Height - 18);
g = Graphics.FromImage(imgCropped);
rOriginal = new Rectangle(0, 0, imgCropped.Width,
imgCropped.Height);
rCropped = rOriginal;

// Copy the subset of the original image to the
cropped image
g.DrawImage(imgOriginal, rCropped, rOriginal,
GraphicsUnit.Pixel);

// Save the cropped image to disk
outFileName = outputDirName + @"\" +
Path.GetFileNameWithoutExtension(fi.Name) + "_cropped.jpg";
imgCropped.Save(outFileName,
System.Drawing.Imaging.ImageFormat.Jpeg);

// Clean up resources
g.Dispose();
imgCropped.Dispose();
imgOriginal.Dispose();
}
catch (IOException ex) {
}
}
}

private static bool IsImageFile(string fileName)
{
return fileName.EndsWith(".jpg") ||
fileName.EndsWith(".gif") ||
fileName.EndsWith(".bmp");
}

Nov 7 '07 #1
1 5623


Bookmark this site:
http://www.bobpowell.net/faqmain.htm

He is daBomb for image related stuff.


"jpuopolo" <pu*****@gmail.comwrote in message
news:11*********************@50g2000hsm.googlegrou ps.com...
All:

I looked around and could not find a simple yet complete example of
cropping an image in C#. I had the problem of needing to shave off the
bottom-most 18 lines of a directory full of images. The following code
does this. I hope that this serves as a concise yet complete example
of how to tackle cropping an image.

---
Note that inputDireName and outputDirName have been set in the class
someplace else.

private static void CropImages()
{
// Get all the files from the source directory

DirectoryInfo di = new DirectoryInfo(inputDirName);
FileInfo[] imageFileNames = di.GetFiles();

// Process each file, one by one
foreach (FileInfo fi in imageFileNames) {

// If this is not an image file, skip it
if (!IsImageFile(fi.FullName)) {
continue;
}

// Take a piece of the orginal image and write it to
the
// cropped image.

Image imgOriginal; // Image read from disk
Bitmap imgCropped; // Image created from original
Rectangle rOriginal; // Source rectangle of
original
Rectangle rCropped; // Destination (cropped)
rectangle
Graphics g; // Graphics surface of
destination image
string outFileName; // Name of cropped image file
written out

try {
// Load the original image
imgOriginal = Image.FromFile(fi.FullName);

// Calculate the cropped image dimensions and
create a surface
// on which to draw it
imgCropped = new Bitmap(imgOriginal.Width,
imgOriginal.Height - 18);
g = Graphics.FromImage(imgCropped);
rOriginal = new Rectangle(0, 0, imgCropped.Width,
imgCropped.Height);
rCropped = rOriginal;

// Copy the subset of the original image to the
cropped image
g.DrawImage(imgOriginal, rCropped, rOriginal,
GraphicsUnit.Pixel);

// Save the cropped image to disk
outFileName = outputDirName + @"\" +
Path.GetFileNameWithoutExtension(fi.Name) + "_cropped.jpg";
imgCropped.Save(outFileName,
System.Drawing.Imaging.ImageFormat.Jpeg);

// Clean up resources
g.Dispose();
imgCropped.Dispose();
imgOriginal.Dispose();
}
catch (IOException ex) {
}
}
}

private static bool IsImageFile(string fileName)
{
return fileName.EndsWith(".jpg") ||
fileName.EndsWith(".gif") ||
fileName.EndsWith(".bmp");
}

Nov 7 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Ralph Freshour | last post by:
Is there anyway to crop .jpg images so that they are all of the same width and height? I use the following math to calculate the correct aspect ratio: width / height == aspect ratio so if I...
1
by: Duncan Smith | last post by:
Hello, Can anyone advise me how to crop an EPS image generated by dislin. I can't figure out how to crop the image before generating it. Using PIL to crop the generated image I get an IOError...
13
by: Jon Yeager | last post by:
I need to display a bunch of pictures that are all of various dimensions into a fixed dimension space, like MSN Messenger does with its user photos in the chat windows. Forcing image dimensions...
3
by: Paul E Collins | last post by:
I need to load a bitmap image, crop it, and save it. By cropping, I don't mean resizing - I mean reducing it to a fixed size area. Image img = Bitmap.FromFile("in.bmp"); // what goes here?...
0
by: AmerS | last post by:
hi, I have been trying to generate image patches for a training set but have not succeded yet. The only method i tried is cropping areas of the image and store the cropped images or patches as an...
2
by: kumari | last post by:
Hi, I am facing a problem with generation of thumbnail images in php. The requirement is as follows: the client would provide the image url, description, and content through a page. and the...
0
by: lalithabhamidi | last post by:
Hai i am using GDIplus and working on VC++ 6.0.Please can u help me on Removing red eye and cropping an Image.I immediately need ur help. Thanks in advance for ur help.
2
by: ykhamitkar | last post by:
Hi there, I am trying to create a game for which I need following information 1. How to add a browse button which would make user able to select an image file and then that image gets added in...
3
by: mcfly1204 | last post by:
I have a photo cropping tool in place that fits my needs, with one exception. When a user uploads a high res. photo, it does not fit on the screen. I have a zoom feature that allows the image to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.