Back to the snippets index

Dividing an image ( Anthony 18/6/2008 )

Make an image look as though it is made up from individual poleroid photos. The image rotations and spacings are random with certain limits so the final image will be slightly different everytime. I have modified the code slightly to use image formats that would not normaly be in the folder miff and bmp. If you have any bmp files in the same folder as this code they will be deleted. This will also improve the quality slightly as I was using jpg format for one set of tempory images before.

IM code:

<?php
// Original image
$image = 'sunflower.jpg';
 
// Amount of images in x
$qty_x = '4';
 
// Amount of images in y
$qty_y = '3';
 
// Get the size of the original image
$size = getimagesize($image);
 
// Size to crop the images to 
$crop_x = round( $size[0]/$qty_x + 0.5);
$crop_y = round( $size[1]/$qty_y + 0.5 );
 
// Canvas for combined images
// It will be trimmed to the finished image size in the code
$width = ( $size[0] * 1.5 );
$height = ( $size[1] *1.5 );
 
// Crop the image - saving as a miff format
exec("convert $image -crop {$crop_x}x{$crop_y} image-%d.miff"); 
 
// Remove the .miff from the filenames
// Replacing it with a bmp to save overwriting the original
foreach (glob("*.miff") as $filename) {
$file = str_replace('.miff', '', $filename );
    exec("convert $filename -background black +polaroid $file.bmp"); 
}
 
// Delete tempory images
foreach (glob("*.miff") as $filename) {
unlink($filename); 
}
 
// Set $command variable
$command = "";
 
// Loop through generating the image layout command
for ($j = 0; $j < $qty_y; $j++) { 
 
  for ($i = 0; $i < $qty_x; $i++) {    $n = $j>0 ? $qty_x*($j)+$i : $i; 
  $offset_x= ( ($crop_x * $i ) + rand(2, 25));
  $offset_y=( ($crop_y * $j ) + rand(2, 25));
  $command .= " image-$n.bmp -geometry +$offset_x+$offset_y -composite" ;  } 
  }
 
// Produce the combined image.
// If saving as a png you could use xc:none for a transparent background
exec( "convert -size {$width}x{$height} xc:#262b38 $command -trim combined.jpg"); 
 
// Delete tempory images
foreach (glob("*.bmp") as $filename) {
unlink($filename); 
}
?>

Image to go with Dividing an image example code
Add borders
Alternative rounded corners
Apply rounded corners to an image
Convert image to black and white
Dividing an image
Improve photos colours
Pencil sketch
Polaroid effect
Transparent gradiant
Venetian blind effect