cut portion of image

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
scts102
Forum Newbie
Posts: 23
Joined: Thu Aug 25, 2005 2:15 pm

cut portion of image

Post by scts102 »

Hello,

I was wondering if it is possable to take an image, crop out a segment, and save that segment as a different file. I looked at the ImageCopy function, but I am sort of lost in it...the php manual does not elaborate much on it.

Here is what I have found:

Code: Select all

int ImageCopy   (resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)
I can understand that it calls for in each parameter, but I am confused on how to set the first two : the resources. At first, I tried inserting a direct file name, but that did not work. Then, I called a variable that stored the fopen() of the image, and that did not work either.

IF this function does what I want it to do, how do I need to call it. If it does not do what I need, how can I accomplish my task?
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

I always say....

Think of your image as a web browser window, the height and width of your image is the same as a web browsers viewable window. To get to a certain position you have to move from the TOP, downward and move LEFT. Where ever you stop, will be the starting position of the new image you will create. The HEIGHT and WIDTH will be the image you cutout starting at the position you moved the window to.


So a simple example....

Code: Select all

<?

// the image we are cutting from (width -> 800,  height -> 600)

$old_image = './old.png';

// old image width

$ow = 800;

// old image height

$oh = 600;

// this will be the new image cutout from the old image

$new_image = './new.png';

// the image size we want to cut out!

$nw = 400; // the width of the new cutout

$nh = 200; // the height of the new cutout

$px = 200; // from the left edge of the old image, this is where we will start the cutout (FROM LEFT)

$py = 300; // from the top edge of the old image, this is where we will start the cutout (FROM TOP)

// create the image resource from the old image

$old = imagecreatefrompng ( $old_image );

// create the image resource for the new cutout image

$new = imagecreatetruecolor ( $nw, $nh );

// now make the cutout, this will cutout a 400x200 cutout from the exact center of the old 800x600 image

imagecopy ( $new, $old, 0, 0, $px, $py, $ow, $oh );

// save the new image cutout

imagepng ( $new, $new_image );

// remove both image resources, free memory

imagedestroy ( $new );
imagedestroy ( $old );

?>

pif!
Post Reply