Reputation: 49
I tried to create something like this site do (slice image into pieces)
<?php
$im = imagecreatefromjpeg('a.jpg');
$height = imagesy($im);
$width = imagesx($im);
$a = 20;
while($a<=$height){
$slice[] = $a;
$a+=20;
}
if($a>$height && end($slice) !== $height){
$slice[] = $a+($height-$a);
}
for($i=0;$i<count($slice);$i++){
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => $slice[$i]]);
if ($im2 !== FALSE) {
imagejpeg($im2, "test/example-$i.jpg");
imagedestroy($im2);
}
}
imagedestroy($im);
echo PHP_EOL .'Fck Yeah'. PHP_EOL;
?>
i wanted to slice image every 20 pixel verticaly, but code above only work on the first only :'(
Thanks
Upvotes: 2
Views: 2302
Reputation: 36
You can replace
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => $slice[$i]]);
with
$im2 = imagecrop($im, ['x' => 0, 'y' => $slice[$i] * $i, 'width' => $width, 'height' => $slice[$i]])
Here is the magic: Your Y axis must be updated each time your loop runs. In your code, Y is always 0. That's why every time you crop a portion, it starts from the top of the main image. By replacing Y static value, Y dynamically changes each time and each image portion's Y axis starts from where the previous cropped portion was cut off.
Upvotes: 2
Reputation: 44
Inside imagecrop function the y
coordinate is always set to 0. Hence while looping the image is cropped from initial coordinate y=0
to $slice[$i]
I would suggest to user following for loop instead:
for($i=0;$i<count($slice);$i++){
$im2 = imagecrop($im, ['x' => 0, 'y' => $slice[$i] - $a, 'width' => $width, 'height' => $slice[$i]]);
if ($im2 !== FALSE) {
imagejpeg($im2, "test/example-$i.jpg");
imagedestroy($im2);
}
}
Upvotes: 2
Reputation: 97672
You're changing the height, you should be changing the y value
...
$a = 0;
while($a<=$height){
$slice[] = $a;
$a+=20;
}
if($a>$height && end($slice) !== $height){
$slice[] = $a+($height-$a);
}
for($i=0;$i<count($slice);$i++){
$im2 = imagecrop($im, ['x' => 0, 'y' => $slice[$i], 'width' => $width, 'height' => 20);
if ($im2 !== FALSE) {
imagejpeg($im2, "test/example-$i.jpg");
imagedestroy($im2);
}
}
...
Upvotes: 1