473,799 Members | 3,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(i nputDirName);
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(f i.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(imgOrigi nal.Width,
imgOriginal.Hei ght - 18);
g = Graphics.FromIm age(imgCropped) ;
rOriginal = new Rectangle(0, 0, imgCropped.Widt h,
imgCropped.Heig ht);
rCropped = rOriginal;

// Copy the subset of the original image to the
cropped image
g.DrawImage(img Original, rCropped, rOriginal,
GraphicsUnit.Pi xel);

// Save the cropped image to disk
outFileName = outputDirName + @"\" +
Path.GetFileNam eWithoutExtensi on(fi.Name) + "_cropped.j pg";
imgCropped.Save (outFileName,
System.Drawing. Imaging.ImageFo rmat.Jpeg);

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

private static bool IsImageFile(str ing fileName)
{
return fileName.EndsWi th(".jpg") ||
fileName.EndsWi th(".gif") ||
fileName.EndsWi th(".bmp");
}

Nov 7 '07 #1
1 5693


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

He is daBomb for image related stuff.


"jpuopolo" <pu*****@gmail. comwrote in message
news:11******** *************@5 0g2000hsm.googl egroups.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(i nputDirName);
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(f i.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(imgOrigi nal.Width,
imgOriginal.Hei ght - 18);
g = Graphics.FromIm age(imgCropped) ;
rOriginal = new Rectangle(0, 0, imgCropped.Widt h,
imgCropped.Heig ht);
rCropped = rOriginal;

// Copy the subset of the original image to the
cropped image
g.DrawImage(img Original, rCropped, rOriginal,
GraphicsUnit.Pi xel);

// Save the cropped image to disk
outFileName = outputDirName + @"\" +
Path.GetFileNam eWithoutExtensi on(fi.Name) + "_cropped.j pg";
imgCropped.Save (outFileName,
System.Drawing. Imaging.ImageFo rmat.Jpeg);

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

private static bool IsImageFile(str ing fileName)
{
return fileName.EndsWi th(".jpg") ||
fileName.EndsWi th(".gif") ||
fileName.EndsWi th(".bmp");
}

Nov 7 '07 #2

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

Similar topics

1
2287
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 need a 268 w x 176 h I do this: target width 268 / aspect ration == correct height
1
1939
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 (apparently because I'm using Windows). I could use other file formats, but I'm not too keen on the results I'm getting from using e.g. .tif. Basically I need to copy (publication quality) images created in dislin and paste them into word...
13
6892
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 will warp the proportions, so that's no good. Forcing one coordinate while leaving the other flexible will maintain proportions, but the x,y values won't be consistant from picture to picture. I considered the MSN Messenger method of bringing...
3
11308
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? img.Save("out.bmp"); img.Dispose();
0
1958
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 array of bytes. The problem is, same patch gets stored thoughout the array, meaning its cropping the same area in the loop and the rectangle is not moving, could some one explain to me why, Thank You. heres the code: MemoryStream stream = new...
2
1787
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 same information will be stored in database. While displaying all images i should take that url. and read it byte by byte and pass to a curl function where in it crops and echos.. the cropped version of image.
0
1198
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
2985
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 the flash file for the game 2. How to split (crop) these images into multiple small boxes Kindly advise Thanks
3
2909
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 fit on the screen, but then the user is cropping the downsized image and not the original. I would like to find a way to have the cropped area on the original image correspond with the cropped area on the zoomed image. Any thoughts? I have...
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10490
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10243
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7570
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.