How to Divide One Image Into Multiple Images Using PHP
So you want to break one large image into multiple smaller images? No problem. This may seem like an obscure problem, but there are multiple reasons you’d want to do this. Maybe you want to create a visual sliding puzzle. Or maybe you are running a unique WordPress theme. Or maybe you want to create a collage of some kind. It really doesn’t matter why you want to split an image into smaller image, PHP makes this task easy. The example below only deals with jpegs. Changing the function to deal with other types of images wouldn’t be that hard.
<?php
//This function will split an image into a number of equally sized columns and rows.
function split_image($number_of_rows, $number_of_cols, $path_to_image, $file_name){
//$number_of_rows = # of rows you want;
//$number_of_cols = # of cols you wnat
//$path_to_image = the path to the folder the image is in, something like: /home/content/username/html/list/uploads/
//$file_name = The filename of the image: archery.jpg, etc.
// parse path for the extension
$info = pathinfo($path_to_image . $file_name);
//make sure we are dealing with a jpeg
if ( (strtolower($info['extension']) == ‘jpg’) || (strtolower($info['extension']) == ‘jpeg’) ){
// load image and get image size
$source = imagecreatefromjpeg( "{$path_to_image}{$file_name}" );
$width = imagesx( $source ); //Find the width
$height = imagesy( $source ); //Find the height
$segment_width = $width/$number_of_cols; //Determine the width of the individual segments
$segment_height = $height/$number_of_rows; //Determine the height of the individual segmentsfor( $col = 0; $col < $number_of_cols; $col++)
{for( $row = 0; $row < $number_of_rows; $row++)
{$fn = sprintf( "img%02d_%02d.jpg", $col, $row );
echo( "$fn" ); //I print the image name here, so that the process shows itself as it runs
$im = @imagecreatetruecolor( $segment_width, $segment_height );
imagecopyresized( $im, $source, 0, 0, $col * $segment_width, $row * $segment_height, $segment_width, $segment_height, $segment_width, $segment_height );
$file = "test.jpg";
//Save the images
if(imagejpeg( $im,"INSERT DESTINATION HERE ", 100 )) //The destination will be something like/home/content/c/h/d/images/$fnecho("Has been made!<br/>");
}
}
}
}
?>






















