phpimagecreatefrompng

Crop a Square Image of 450x450 into 9 pieces of 150x150 each, using PHP


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?


Solution

  • 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);