Important alert: (current site time 10/31/2014 6:55:52 AM EDT)
 

VB icon

Auto Crop Images

Email
Submitted on: 11/13/2003 4:37:02 PM
By: dotNETJunkie  
Level: Intermediate
User Rating: By 5 Users
Compatibility: VB.NET, ASP.NET
Views: 86702
(About the author)
 
     This is source code for a function that you can pass an image to and return a dynamically cropped version of the image without the excess space. I needed to do this at work, where we had logos in our information system. The logos needed to be pulled, after updates were made, and used in our web portal. The problem was that many of the images had excess space to one or more sides, which in turn did not want to center properly when the image was placed on the web. I looked around the web, but found next to nothing. I ended up finding a PSC post (http://planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=518&lngWId=10) for changing the background color, I modified to code to search for the furthest X and Y coordinates on all sides to find where the image began. Then I rewrote the image without the extra space. Please vote and leave comments/feedback!

 
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
//**************************************
// for :Auto Crop Images
//**************************************
'Code Inspired by PSC post http://planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=518&lngWId=10
'Posted by The New iSoftware Company!
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: Auto Crop Images
// Description:This is source code for a function that you can pass an image to and return a dynamically cropped version of the image without the excess space.
I needed to do this at work, where we had logos in our information system. The logos needed to be pulled, after updates were made, and used in our web portal.
The problem was that many of the images had excess space to one or more sides, which in turn did not want to center properly when the image was placed on the web.
I looked around the web, but found next to nothing. I ended up finding a PSC post (http://planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=518&lngWId=10) for changing the background color, I modified to code to search for the furthest X and Y coordinates on all sides to find where the image began. Then I rewrote the image without the extra space.
Please vote and leave comments/feedback!
// By: dotNETJunkie
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=1755&lngWId=10//for details.//**************************************

Function Crop(ByVal p As Image) As Image
 Dim x, y As Int32 'for use of X,Y Coordinates of pixels
 Dim b As New Bitmap(p) 'image needed to crop
 Dim c As New Color() 'pixel color for use of identifying if background
 
 Dim intLeft As Int32 'furthest left X coordinate
 Dim intRight As Int32 'furthest right X coordinate
 Dim intBottom As Int32 'furthest to the bottom Y coordinate
 Dim intTop As Int32 'furthest to top Y coordinate
 y = 0
 Do Until y = b.Height 'loop through pixels on Y axis until end of image height
 x = 0
 Do Until x = b.Width 'loop through pixels on X axis until end of image width
 c = b.GetPixel(x, y) 'Get the color of the pixel
 'First we want to establish if the pixel is White (the color of our background)
 If c.R <> 0 And c.G <> 0 And c.B <> 0 Then
'We'll also want to ignore colors close to the background color
'I did this because some of the images I had were scanned, and 
'the paper color didn't always scan at a perfect white
If c.R < 250 Or c.G < 250 Or c.B < 250 Then
'Determine if pixel is further left than the value we already have
If intLeft <= 0 And intLeft < x Then
intLeft = x
End If
'Determine if pixel is further to the top than the value we already have
If intTop <= 0 And intTop < y Then
intTop = y
End If
'Determine if pixel is further right than the value we already have
If intRight <= b.Width And intRight < x Then
intRight = x
End If
'Determine if pixel is further to the bottom than the value we already have
If intBottom <= b.Height And intBottom < y Then
intBottom = y
End If
End If
 End If
 x += 1
 Loop
 y += 1
 Loop
 Dim intNewWidth As Int32 = (intRight) 'Establish width of new cropped image
 Dim intNewHeight As Int32 = (intBottom) 'Establish height of new cropped image
 'Create new image with a 10 pixel buffer, so image won't be too close to edge
 Dim imgCropped As New Bitmap(intNewWidth + 10, intNewHeight + 10)
 'Create a Graphics object for drawing to the cropped image
 Dim objGraphics As Graphics = Graphics.FromImage(imgCropped)
 'set the background color to white (you can choose what you like
 objGraphics.Clear(System.Drawing.Color.White)
 'Determine where you'd like to start drawing from the Top (Y axis)
 Dim intStartTop As Int32 = 5 '-intTop / 40 + 5
 'Determine where you'd like to start drawing from the Left (X axis)
 Dim intStartLeft As Int32 = 5 '-intLeft / 40 + 5
 'you want to start drawing the image at the point where an actual image exists,
 'not just blank space. I negated the furthest top and left pixel points and
 'divided them by 40 and added 5 (half of the 10 pixel buffer, so 5x on each side)
 'The reason I divided was because the image would be too far to the left or top
 'sometimes and 40 just happened to work the best for the images I was cropping.
 'I believe this has to do with the horizontal an vertical resolution values,
 'bit depth, and image format
 'There must be room for improvement or a way to do this better, but it worked for
 'what I needed.
 'Draw the original image to your new cropped sized image
 objGraphics.DrawImage(b, intStartLeft, intStartTop)
 b.Dispose()
 objGraphics.Dispose()
 'return the Cropped image to the caller
 Return imgCropped
 End Function


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

11/19/2003 11:23:57 AM

This is interesting source code. However, the code is using the getpixels( ) method in GDI+ which is horribly slow. I have done tests with that. The recommended way of doing something like this with the .NET Framework and GDI+ is to use the lockbits( ) and unlockbits( ) methods to stream the data to memory for quicker analysis.
(If this comment was disrespectful, please report it.)

 
11/19/2003 11:26:15 AMdotNETJunkie

Thanks for the tip. I'm fairly new to the graphics end of programming. Much has been databases and web apps. I'll look into this and fix up the code. Thanks
(If this comment was disrespectful, please report it.)

 
5/18/2004 4:56:07 AM

How do i Save the newly created image to disk?

(If this comment was disrespectful, please report it.)

 
5/18/2004 4:56:46 AM

How do i Save the newly created image
to disk?

(If this comment was disrespectful, please report it.)

 
5/18/2004 9:59:08 AMdotNETJunkie

The image object that is used and returned has a save method. So if you wanted to convert this function to save, you can simply use...

imgCropped.Save("C:\Location\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

You can save to different formats besides jpeg too.
(If this comment was disrespectful, please report it.)

 
12/9/2004 9:33:36 AMfallofempires

you are brilliant!
(If this comment was disrespectful, please report it.)

 
3/30/2005 3:55:57 AM

success
(If this comment was disrespectful, please report it.)

 
3/30/2005 3:57:20 AM

success_770@hotmail.com
(If this comment was disrespectful, please report it.)

 
5/8/2006 3:39:50 AMmbedford

This code looks excellent. What are the parameters to modify if i want to crop out a black (or in that area) background instead of white?
(If this comment was disrespectful, please report it.)

 
10/22/2006 7:23:46 PMODeN

You cab specify the color to crop by changing "c.R <> 0 And c.G <> 0 And c.B <> 0 ". Change the 0's to 255 and it should now look for black.
(If this comment was disrespectful, please report it.)

 
2/22/2007 3:01:26 PMRSmithers

If you would like, I have used this code for a project of my own and updated it using lockbits and can forward it to you. It was way too slow for the now common 5+ megapixel images we regularly deal with. Using the lockbits method shortened the time to execute from about 10 minutes to 10 seconds.
(If this comment was disrespectful, please report it.)

 
2/23/2012 11:14:25 AMeeBee

Hi, I found a more elegant and faster way to autocrop.
What I do is to find the first pixel that's not the background color on the left.
Once the pixel is found, I then look for the one on the top, then the right and finalle the bottom.
this way I don't need to scan the whole image.

As ther's no space to put the code here, just contact me, and I'll send it to you...
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.