hussy hanif
hussy hanif

Reputation: 21

Split Image Into Required Parts PHP

I'm new in PHP

I need to split image into Required number of pieces

$ImagesRequired = $_GET['id'];
$source = @imagecreatefromjpeg( "check.jpg" ); 
$source_width = imagesx( $source ); 
$source_height = imagesy( $source );

$width = $source_width / ($ImagesRequired / 2) ; 
$height = $source_height / ($ImagesRequired / 2);

for( $col = 0; $col < $ImagesRequired / 2; $col++) { 
   for( $row = 0; $row < $ImagesRequired / 2; $row++) { 
      $fn = sprintf( "testing/img%02d_%02d.jpg", $col, $row ); 
      echo( "$fn\n" ); $im = @imagecreatetruecolor( $width, $height ); 
      imagecopyresized( $im, $source, 0, 0, $col * $width, $row * $height, $width, $height, $width, $height ); 
      imagejpeg( $im, $fn ); 
      imagedestroy( $im ); 
   } 
}

When i used required number "$ImagesRequired = 4" its working perfect but when i used "$ImagesRequired =6" the image in split into 9 pieces

Upvotes: 2

Views: 89

Answers (1)

RocketNuts
RocketNuts

Reputation: 11130

You are taking $ImagesRequired / 2 as the number of rows and columns, but this is wrong. Because the total number of resulting images will be columns * rows, not columns + rows.

Ideally you should have √$ImagesRequired (the square root of $ImagesRequired) which is sqrt($ImagesRequired) as the number of rows and columns, but this is only possible if $ImagesRequired is a square number.

Contemplate for yourself: how many rows and columns would you expect if $ImagesRequired is 7?

You need to algorithmically find a number of rows and columns to match ($rows * $columns) == $ImagesRequired.

To suggest an approach:

  1. start with $columns = round(sqrt($ImagesRequired))
  2. take $rows = round($ImagesRequired) / $columns
  3. if ($rows * $columns) == $ImagesRequired you're done
  4. decrease $columns by 1 and go back to step 2.

Note that this assumes the smaller images (the 'cells' in your rows and columns so to speak) to be in the same width:height proportions as the original image.

If you want something else, for example keeping the smaller images as square as possible, you need to take this into account in determining the optimal starting $columns and $rows ratio.

Also keep in mind that it may not be possible to have the exact same width and height for every sub-image. For example, if your original image is 201 x 201 pixels, and $ImagesRequired is 4, what kind of sub-images do you expect?

Upvotes: 2

Related Questions