3

I have an source image of 450x450 px. And i want to crop it into 9 peices of 150x150 each using PHP.
I am using the following code.
I am getting 9 images, but cropping is not appropriate. Here is the screen shot :

enter image description here

Last one is the source image i am using.
Here is my Code.

<?php

$targ_w = $targ_h = 150;
$jpeg_quality = 25;

$src = "puzzleimages/puzzle2.jpg";

$y = 0;
$y2 = 150;
$x = 0;
$x2 = 150;

$i = 3;
$name = 0;
while( $i-- ){
    $j = 3;

    while( $j-- ){


        $img_r = imagecreatefromjpeg($src);
        $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

        imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$x2,$y2);

        //header('Content-type: image/jpeg');
        imagejpeg($dst_r,'puzzleimages/'.++$name.'.jpg', $jpeg_quality);

        $x += 150;
        $x2 += 150;

    }


    $y += 150;
    $y2 += 150;
    $x = 0;
    $x2 = 150;

}

?>

Can anyone suggest what is going wrong?

jackkorbin
  • 491
  • 7
  • 22

2 Answers2

2

I don't think you need to keep changing the source width/height, and it should be 150 all the time. Give this a try:

imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$targ_w,$targ_h);
James
  • 20,957
  • 5
  • 26
  • 41
1
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int$dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

Refer to Php documentation, the only parameters need to be changed are src_x and src_y. Since you changed your x2 and y2, the following will be applied:

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed.

zc246
  • 1,514
  • 16
  • 28