DJ Mike's Tutorials: PHP

The ImagickPixelIterator class Example #1: Ripple


^ >

  
Text

To create the ripple effect in the image above I created a function named "ripple" which accepts three arguments: an image, amplitude and wave length. The function will find the center of the image, clone the image then for every pixel it will calculate the distance from the center, get the pixel's color and darken or lighten the color based on the sine of it's distance from the center.

<?
/* 
ripple() returns a rippled image
Requires 3 arguments: $file, $amplitude and $wavelength.
• file = file path
• amplitude: Adds/subtracts to color. 
• wavelength: Multiplies wavelength
*/ 
########################################
function ripple$file$amplitude$wavelength

# create image object
$image = new Imagick("$file");
# Get stats of original image
$w $image->getimagewidth();
$h $image->getimageheight();
$type $image->getimageformat();
# find the center
$center_x $w/2;
$center_y $h/2;
# clone image to use as palette
$copy $image->clone();
# Get ImagickPixelIterator 
$it $image->getPixelIterator(); 
# Reset the iterator to begin 
$it->resetIterator(); 
# start cooridinate counters
$x 0;
# Loop as long as there is a next row  
while( $row $it->getNextIteratorRow() ) 
 { 
 
$x 0# reset $x at end of row
 # Loop through columns 
 
foreach ($row as $pixel
  { 
   
##################################################
   # This is the part that acts on all pixels in an image
   ##################################################
   
$color $pixel->getcolor(); # get $color as an array
   # $d = distance from center
   
$d hypot(abs($center_x-$x), abs($center_y-$it->getIteratorRow()));
   
$d rad2deg($d);
   
$d $d/$wavelength;
   
$sin $amplitude*sin($d);
   
#### modify color ####
   
$point = new ImagickPixel();
   
$red $color[r]+$sin;
   
$green $color[g]+$sin;
   
$blue $color[b]+$sin;
   
$point->setcolor("rgb($red,$green,$blue)");
   
#### new draw object ####
   
$draw_point = new imagickdraw();
   
$draw_point->setfillcolor($point);
   
$draw_point->point$x$it->getIteratorRow() );
   
# draw the point on the clone
   
$copy->drawimage($draw_point);
   
##################################################
   
$x++;
   } 
# end column loop
  
# end row loop
 ########################################
 # This is where you output the clone
 
header"content-type:image/$type);
 echo 
$copy;
 
########################################
# end function

# execute the ripplefunction
ripple"opossum.jpg"30200 );
?>

^ >

Was this webpage useful to you? You can support this website by donating.


Created by DJ Mike from Santa Barbara

DJ Mike


<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>