Getting RGBA Pixel Data From ColdFusion Images Using GetPixels()

Posted February 18, 2008 at 7:00 AM

Tags: ColdFusion

This weekend, I added two more user defined functions to the ImageUtils.cfc ColdFusion component for image manipulation:

  • GetPixel()
  • GetPixels()

GetPixels() takes a ColdFusion image and returns an array or arrays that contains a structure for each sampled pixel. These structures contain a Red, Green, Blue, Alpha, and Hex key for the Red, Green, Blue, and Alpha channels respectively and the Hex for the 6 digit hexadecimal encoding of the color. By default, if you just pass in the ColdFusion image, GetPixels() will return the pixel data for the entire image. However, you have the option to pass in a starting X and Y coordinate as well as the width and height of the desired sample area:

GetPixels( Image [, X [, Y [, Width [, Height ] ] ] ] ) :: Array

This leverages the underlying Java AWT buffered image object; I am no master of this library, so this might not be the most performant utility function. It will, however, provide me with tools that I will leverage in the authoring of future utility functions.

Let's take a look at an example of how this works. In the demo below, we will take this image:


 
 
 

 
Cute Sexy Blonde Used In The ImageUtils.cfc Examples  
 
 
 

... and sample a 50px by 50px area in the middle of the image. Then, we will loop over that sample and output it in 3 by 3 divs:

 Launch code in new window » Download code as text file »

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>GetPixels()</title>
  •  
  • <style type="text/css">
  •  
  • div.canvas {
  • background-color: #333333 ;
  • border: 1px solid #000000 ;
  • float: left ;
  • padding: 1px 0px 0px 1px ;
  • }
  •  
  • div.row {
  • clear: both ;
  • height: 3px ;
  • margin-bottom: 1px ;
  • overflow: hidden ;
  • }
  •  
  • div.pixel {
  • float: left ;
  • font-size: 1px ;
  • height: 3px ;
  • line-height: 1px ;
  • margin: 0px 1px 0px 0px ;
  • overflow: hidden ;
  • width: 3px ;
  • }
  •  
  • </style>
  • </head>
  • <body>
  •  
  •  
  • <!--- Create the image utils object. --->
  • <cfset objImageUtils = CreateObject( "component", "imageutilsroot.imageUtils" ).Init() />
  •  
  • <!--- Read in the cute blonde image. --->
  • <cfimage
  • action="read"
  • source="../cute_blonde.jpg"
  • name="objImage"
  • />
  •  
  • <!--- Read in 50 x 50 pixels. --->
  • <cfset arrPixels = objImageUtils.GetPixels(
  • objImage,
  • 200,
  • 185,
  • 50,
  • 50
  • ) />
  •  
  •  
  • <cfoutput>
  •  
  • <div class="canvas">
  •  
  • <!--- Loop or y axis. --->
  • <cfloop
  • index="intY"
  • from="1"
  • to="#ArrayLen( arrPixels )#"
  • step="1">
  •  
  • <div class="row">
  •  
  • <!--- Loop over x axis. --->
  • <cfloop
  • index="intX"
  • from="1"
  • to="#ArrayLen( arrPixels[ intY ] )#"
  • step="1">
  •  
  • <!--- Get the pixel short-hand from the array. --->
  • <cfset objPixel = arrPixels[ intY ][ intX ] />
  •  
  • <div
  • class="pixel"
  • style="background-color: ###objPixel.Hex#;"
  • ></div>
  •  
  • </cfloop>
  •  
  • </div>
  •  
  • </cfloop>
  •  
  • </div>
  •  
  • </cfoutput>
  •  
  • </body>
  • </html>

Running this code, we get the following pixilated output:


 
 
 

 
Cute Sexy Blonde Girl Drawn In 3x3 Pixel Divs  
 
 
 

As you can see, each pixel is drawn using a 3px by 3px div with an explicit background color using the HEX value returned from the function.

Here is the code behind this functionality:

 Launch code in new window » Download code as text file »

  • <cffunction
  • name="GetPixels"
  • access="public"
  • returntype="array"
  • output="false"
  • hint="Returns a two dimensional array of RGBA values for the image. Array will be in the form of Pixels[ Y ][ X ] where Y is along the height axis and X is along the width axis.">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="Image"
  • type="any"
  • required="true"
  • hint="The ColdFusion image object whose pixel map we are returning."
  • />
  •  
  • <cfargument
  • name="X"
  • type="numeric"
  • required="false"
  • default="1"
  • hint="The default X point where we will start getting our pixels (will be translated to 0-based system for Java interaction)."
  • />
  •  
  • <cfargument
  • name="Y"
  • type="numeric"
  • required="false"
  • default="1"
  • hint="The default Ypoint where we will start getting our pixels (will be translated to 0-based system for Java interaction)."
  • />
  •  
  • <cfargument
  • name="Width"
  • type="numeric"
  • required="false"
  • default="#ImageGetWidth( ARGUMENTS.Image )#"
  • hint="The width of the area from which we will be sampling pixels."
  • />
  •  
  • <cfargument
  • name="Height"
  • type="numeric"
  • required="false"
  • default="#ImageGetHeight( ARGUMENTS.Image )#"
  • hint="The height of the area from which we will be sampling pixels."
  • />
  •  
  • <!--- Define the local scope. --->
  • <cfset var LOCAL = {} />
  •  
  • <!--- Define the pixels array. --->
  • <cfset LOCAL.Pixels = [] />
  •  
  • <!---
  • Get the image data raster. This holds all the data
  • for the buffered image and will give us access to the
  • individual pixel data.
  • --->
  • <cfset LOCAL.Raster = ImageGetBufferedImage( ARGUMENTS.Image ).GetRaster() />
  •  
  •  
  • <!---
  • Now, starting at our Y position, we want to move down
  • each column (Y-direction) and gather the pixel values
  • for each row along the Y-axis.
  • --->
  • <cfloop
  • index="LOCAL.Y"
  • from="#ARGUMENTS.Y#"
  • to="#(ARGUMENTS.Y + ARGUMENTS.Height - 1)#"
  • step="1">
  •  
  • <!---
  • Create a nested array for this row of pixels.
  • Remember, the data will be in the Pixel[ Y ][ X ]
  • array format.
  • --->
  • <cfset ArrayAppend(
  • LOCAL.Pixels,
  • ArrayNew( 1 )
  • ) />
  •  
  • <!---
  • Loop over this row of pixels at this given Y-axis
  • position.
  • --->
  • <cfloop
  • index="LOCAL.X"
  • from="#ARGUMENTS.X#"
  • to="#(ARGUMENTS.X + ARGUMENTS.Width - 1)#"
  • step="1">
  •  
  • <!---
  • Create an In-array to be used to retreive the
  • color data. Each element will be used for the
  • Red, Green, Blue, and Alpha channels respectively.
  • Be sure to use the JavaCast() here rather than
  • when we pass in the array to the GetPixel()
  • method. This way, we don't lose the reference
  • to the array value.
  • --->
  • <cfset LOCAL.PixelArray = JavaCast(
  • "int[]",
  • ListToArray( "0,0,0,0" )
  • ) />
  •  
  • <!--- Get the pixel data array. --->
  • <cfset LOCAL.Raster.GetPixel(
  • JavaCast( "int", (LOCAL.X - 1) ),
  • JavaCast( "int", (LOCAL.Y - 1) ),
  • LOCAL.PixelArray
  • ) />
  •  
  • <!---
  • Now that we have an index-based pixel data
  • array, let's convert the the data into a keyed
  • struct that will be more user friendly.
  • --->
  • <cfset LOCAL.Pixel = {
  • Red = LOCAL.PixelArray[ 1 ],
  • Green = LOCAL.PixelArray[ 2 ],
  • Blue = LOCAL.PixelArray[ 3 ],
  • Alpha = LOCAL.PixelArray[ 4 ],
  • Hex = ""
  • } />
  •  
  • <!--- Set the HEX value based on the RGB. --->
  • <cfset LOCAL.Pixel.Hex = UCase(
  • Right( "0#FormatBaseN( LOCAL.Pixel.Red, '16' )#", 2 ) &
  • Right( "0#FormatBaseN( LOCAL.Pixel.Green, '16' )#", 2 ) &
  • Right( "0#FormatBaseN( LOCAL.Pixel.Blue, '16' )#", 2 )
  • ) />
  •  
  •  
  • <!--- Add this pixel data to curren row. --->
  • <cfset ArrayAppend(
  • LOCAL.Pixels[ ArrayLen( LOCAL.Pixels ) ],
  • LOCAL.Pixel
  • ) />
  •  
  • </cfloop>
  •  
  • </cfloop>
  •  
  •  
  • <!--- Return pixels. --->
  • <cfreturn LOCAL.Pixels />
  • </cffunction>

In addition to this function, I also created a GetPixel() function that utilizes the GetPixels() function to return the RGBA values for a single pixel:

 Launch code in new window » Download code as text file »

  • <cffunction
  • name="GetPixel"
  • access="public"
  • returntype="struct"
  • output="false"
  • hint="Returns a struct containing the given pixel RGBA data.">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="Image"
  • type="any"
  • required="true"
  • hint="The ColdFusion image object whose pixel data map we are returning."
  • />
  •  
  • <cfargument
  • name="X"
  • type="numeric"
  • required="true"
  • hint="The X coordinate of the pixel that we are returning."
  • />
  •  
  • <cfargument
  • name="Y"
  • type="numeric"
  • required="true"
  • hint="The Y coordinate of the pixel that we are returning."
  • />
  •  
  • <!--- Define the local scope. --->
  • <cfset var LOCAL = {} />
  •  
  • <!--- Get the pixels array for a 1x1 area. --->
  • <cfset LOCAL.Pixels = GetPixels(
  • ARGUMENTS.Image,
  • ARGUMENTS.X,
  • ARGUMENTS.Y,
  • 1,
  • 1
  • ) />
  •  
  • <!--- Return the first returned pixel. --->
  • <cfreturn LOCAL.Pixels[ 1 ][ 1 ] />
  • </cffunction>

This returns a single instance of the pixel structure which looks like this:


 
 
 

 
GetPixel() CFDump Output Of RGBA Data For Given Pixel  
 
 
 

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page





Reader Comments

Feb 18, 2008 at 10:44 AM // reply »
36 Comments

That is really cool! (though I can't quite think of a use for it)


Feb 18, 2008 at 10:50 AM // reply »
7,572 Comments

@Steve,

I actually started coding it with another method in mind. Soon, I will come out with TrimCanvas(). This will remove rows and columns from the edges until it hits "real image content". Basically, this is a way of shrinking a canvas to the smallest possible box without cropped image data.

In FireWorks, this would be CTRL+ALT+T. I figure, I can perform this by sampling pixels until I find one that is not the same as the background color.

Now, not sure if that function will have a use, but I think it will, especially when you do a lot of programmatic pasting of images.


Feb 18, 2008 at 10:57 AM // reply »
36 Comments

*that* is nice! (definitely useful)

So you can get the background color of an image separately?

Can you change the background color for index transparency gifs?


Feb 18, 2008 at 11:21 AM // reply »
7,572 Comments

@Steve,

I am not sure if you can get the background color of an image since I don't think that is really stored in any capacity once the background is drawn. I might have to end up passing in the background color as a hint:

TrimCanvas( Image, CanvasColor )

As far as working with transparent GIF images, I guess you could create an alpha canvas and then paste the GIF onto that canvas? I am not exactly sure what you are asking.


Feb 18, 2008 at 11:25 AM // reply »
36 Comments

Sorry, my thought only made sense on the assumption that you could have read and write access to a background color property which doesn't seem to be the case.

Still, very nifty. I am eager to see how it comes out.


Mar 11, 2008 at 4:13 PM // reply »
1 Comments

Sweet hack.


Jan 29, 2010 at 11:35 AM // reply »
5 Comments

Just posted a Tweet asking for help getting the values of pixels from an image.

Knew i should have just looked on here first.

Excellent post.. and exactly what i was looking for


Jan 29, 2010 at 11:37 AM // reply »
7,572 Comments

@Jbuda,

Awesome, glad to help :)


Jan 29, 2010 at 12:19 PM // reply »
5 Comments

Hi Ben

Just looking at the code.. how would i get the dominant colour on the entire image?

Would i just slice the image up and the loop through each fragment and tally up the colours in an struct?

The struct with most colours is the winner?


Jan 29, 2010 at 10:47 PM // reply »
7,572 Comments

@Jbuda,

I am not sure what you mean by dominant color? You mean like between Red, Green, and Blue? Or are you talking about a particular RGB combination?


Post Comment  |  Ask Ben

Recent Blog Comments
Mar 21, 2010 at 8:57 PM
The Bourne Ultimatum Starring Matt Damon And Julia Stiles
late to the party, but my observation is this: rewatch carefully for the platonic nature of the relationship between nicki and jason. she never flirts with him. he never comes on to her. they alway ... read »
Mar 21, 2010 at 7:40 PM
Is Simulating User-Input Events With jQuery Ever A Good Idea?
A couple of things. One you embed the initial state of of more-info in the CSS. IMHO, that behavior should be in jQuery: moreInfo.hide(); It shows that the behavior your toggling and closing is mor ... read »
Mar 21, 2010 at 3:59 PM
Exploring ColdFusion Component Runtime Class Properties And Serialization
@Elliott, according to Ben's experiment, serializeJSON() doesn't access the private data by default - it doesn't even access the getHair() method - so trying to clone a Girl.cfc via serializeJSON/des ... read »
Mar 21, 2010 at 3:49 PM
Ask Ben: Javascript String Replace Method
I'm confused a bit by what you are asking, but if had this sentence: The color, red, is in the style statement; style: red;. and wanted to remove all or change all of the commas, colons, and semi-c ... read »
Mar 21, 2010 at 3:13 PM
Ask Ben: Javascript String Replace Method
I am trying to make a java program to count the number of times that these punctuation marks occur in a body of text: , : ; . ! - ' " ? / \ I am using this piece to ferret out the commas: numcommas ... read »
Mar 21, 2010 at 11:13 AM
A New Wrist Pain
@chiropractor suwanee, Spoken like someone trying to sell something. Other than for minor, temporary relief from some back pain, chiropractic treatment is nothing but placebo effect and quackery. ... read »
Mar 21, 2010 at 6:32 AM
ColdFusion CFPOP - My First Look
Apologies... The field name in the db for C. is "BounceCode" It stores the code / message which is returned in the email. Sorry for the confusion. ... read »
Mar 21, 2010 at 6:29 AM
ColdFusion CFPOP - My First Look
@Jose Galdamez, Hi Ben and Jose 1st of all.. big thanks to Jose for his Skype chat a few weeks back. Your time was much appreciated. I have come up with a rather unelegant solution to my problem a ... read »