I'm trying to use the IMagick PHP wrapper to assist in chopping a specified image into a set of tiles (the number of which is variable).
In the ImageMagick documentation there is reference to the -crop
operator accepting an optional flag of @
that will instruct it to cut an image into "roughly equally-sized divisions" (see here), solving the problem of what to do when the image size is not an exact multiple of the desired tile size.
Does anyone know if there is a way to leverage this functionality in the IMagick PHP wrapper? Is there anything I can use besides cropImage()
?
I had to do the same thing (if I'm reading your question correctly). Although it does use cropImage...
function slice_image($name, $imageFileName, $crop_width, $crop_height)
{
$dir = "dir where original image is stored";
$slicesDir = "dir where you want to store the sliced images;
mkdir($slicesDir); //you might want to check to see if it exists first....
$fileName = $dir . $imageFileName;
$img = new Imagick($fileName);
$imgHeight = $img->getImageHeight();
$imgWidth = $img->getImageWidth();
$crop_width_num_times = ceil($imgWidth/$crop_width);
$crop_height_num_times = ceil($imgHeight/$crop_height);
for($i = 0; $i < $crop_width_num_times; $i++)
{
for($j = 0; $j < $crop_height_num_times; $j++)
{
$img = new Imagick($fileName);
$x = ($i * $crop_width);
$y = ($j * $crop_height);
$img->cropImage($crop_width, $crop_height, $x, $y);
$data = $img->getImageBlob();
$newFileName = $slicesDir . $name . "_" . $x . "_" . $y . ".jpg";
$result = file_put_contents ($newFileName, $data);
}
}
}