<?php
/**
 * @param $src_filename
 * @param int $cols
 * @param int $gaps
 */
function my_slice($src_filename, $cols = 5, $gaps = 10) {
    $src = imagecreatefromjpeg($src_filename);
    $width = imagesx($src);
    $height = imagesy($src);
    $image = imagecreatetruecolor($width, $height);
    $shadow_base_color = imagecolorallocate($image, 150, 150, 150);
    $shadow_x_shift = $shadow_y_shift = 7;
    $shadow_blur = 15;
    // background color
    $background_color = imagecolorallocate($image, 255, 255, 255);
    imagefill ($image, 0 ,0, $background_color);
    // make shadow rectangles
    $columns = calcColumnsCoords($cols, $gaps, $width, $height);
    foreach ($columns as $col) {
        imagefilledrectangle(
            $image,
            $col['x1'] + $shadow_x_shift, $col['y1'] + $shadow_y_shift,
            $col['x2'] + $shadow_x_shift, $col['y2'] + $shadow_y_shift,
            $shadow_base_color
        );
    }
    // blur them
    $gaussian = array([1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]);
    for ($i = 0; $i < $shadow_blur; $i++) imageconvolution($image, $gaussian, 16, 0);
    // copy original rectangles
    foreach ($columns as $col) {
        imagecopy($image, $src,
            $col['x1'], $col['y1'],
            $col['x1'], $col['y1'],
            $col['x2'] - $col['x1'], $col['y2'] - $col['y1']
        );
    }
    return $image;
}
/**
 * @param int $cols
 * @param int $gaps percent of img sacrificed for gaps between columns
 * @param int $width image width
 * @param int $height image height
 * @return array coordinates of columns corners
 */
function calcColumnsCoords($cols, $gaps, $width, $height) {
    $gap_width = ceil($width / 100 * $gaps / ($cols + 1)); // distance between columns in px
    $col_width = floor(($width - $gap_width * ($cols+1)) / $cols);
    $mid_col = ceil($cols / 2);
    $col_heights = [$height - $gap_width * 2];
    for ($i = 1; $i < $mid_col; $i++) {
        $col_heights[$i] = round($col_heights[$i-1] * 0.62); // 62% - golden ratio
    }
    $columns = [];
    for ($col = 1; $col <= $cols; $col++) {
        $x1 = $gap_width * $col + ($col_width * ($col - 1));
        $x2 = $x1 + $col_width;
        $distance = calcDistanceFromCenter($col, $cols);
        $y1 = round(($height - $col_heights[$distance]) / 2);
        $y2 = $y1 + $col_heights[$distance];
        $columns[] = [
          'x1' => $x1,
          'x2' => $x2,
          'y1' => $y1,
          'y2' => $y2,
        ];
    }
    return $columns;
}
/**
 * @param int $col current column number
 * @param int $cols total columns
 * @return int
 */
function calcDistanceFromCenter($col, $cols) {
  $mid = (int) ceil($cols / 2);
  if ($col <= $mid) return $mid - $col;
  else              return $col - $mid -
                                (~$cols & 1); // 1 if $cols is even
}
header('Content-Type: image/jpg');
imagejpeg(my_slice('orig.jpg', 7), null, 100);