Flipping an Image


More graphics manipulation power is available; for example, the imagecopy function lets you copy all or part of an image:

 imagecopy ( resource dest_image, resource src_image, int dest_x, int dest_y, int src_x, int src_y, int src_w, int src_h) 

This function copies a part of src_image onto dest_image starting at the coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the coordinates dest_x and dest_y.

This function is very handy when you want to manipulate images on a pixel-by-pixel basis. Here's an example where we'll flip an image, image.jpg (from the previous chunk), horizontally. We read in that image with imagecreatefromjpeg and get its size with imagesx and imagesy:

 $image_original = imagecreatefromjpeg("image.jpg"); $image_width = imagesx($image_original); $image_height = imagesy($image_original); 

Then we can create a new image of the same dimensions, $image_new, and set up a nested for loop to loop over every pixel in the image:

 $image_original = imagecreatefromjpeg("image.jpg"); $image_width = imagesx($image_original); $image_height = imagesy($image_original); $image_new = imagecreate($image_width, $image_height); for ($col = 0 ; $col < $image_width ; $col++) {     for ($row = 0 ; $row < $image_height ; $row++)     {         .         .         .     } } 

Finally, we'll use imagecopy inside this nested for loop to copy individual pixels from one image to the new image, reversing the image as we do so, as you can see in phpimageflip.php, Example 13.

Example 13. Flipping an image, phpimageflip.php
 <?     $image_original = imagecreatefromjpeg("image.jpg");     $image_width = imagesx($image_original);     $image_height = imagesy($image_original);     $image_new = imagecreate($image_width, $image_height);     for ($col = 0 ; $col < $image_width ; $col++)     {         for ($row = 0 ; $row < $image_height ; $row++)         {             imagecopy($image_new, $image_original, $image_width - $col - 1,                 $row, $col, $row, 1, 1);         }     }     imagejpeg($image_new);     imagedestroy($image_original);     imagedestroy($image_new); ?> 

The flipped image appears in Figure 14, phpimageflip.html. Not bad. As you can see, this kind of pixel-by-pixel graphics manipulation is very powerful.

Figure 14. Flipping an image.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net