Skip to content

Instantly share code, notes, and snippets.

@angeloped
Created December 16, 2019 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angeloped/498691c76f672cf9eb9be2f707eaa0b9 to your computer and use it in GitHub Desktop.
Save angeloped/498691c76f672cf9eb9be2f707eaa0b9 to your computer and use it in GitHub Desktop.
Crop image from center and output a square cropped image; written in PHP language.
<?php
function cropAlign($image, $cropWidth, $cropHeight, $horizontalAlign = 'center', $verticalAlign = 'middle') {
$width = imagesx($image);
$height = imagesy($image);
$horizontalAlignPixels = calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
$verticalAlignPixels = calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
return imageCrop($image, [
'x' => $horizontalAlignPixels[0],
'y' => $verticalAlignPixels[0],
'width' => $horizontalAlignPixels[1],
'height' => $verticalAlignPixels[1]
]);
}
function calculatePixelsForAlign($imageSize, $cropSize, $align) {
switch ($align) {
case 'left':
case 'top':
return [0, min($cropSize, $imageSize)];
case 'right':
case 'bottom':
return [max(0, $imageSize - $cropSize), min($cropSize, $imageSize)];
case 'center':
case 'middle':
return [
max(0, floor(($imageSize / 2) - ($cropSize / 2))),
min($cropSize, $imageSize),
];
default: return [0, $imageSize];
}
}
// Put your image here
$fname = "a.jpg";
// Get dimensions of the coriginal image
$imgsz = getimagesize($fname);
$minsz = min($imgsz[0], $imgsz[1]);
// Determine image mime type
if(exif_imagetype($fname) != IMAGETYPE_JPEG){
// For PNG
$im = imagecreatefrompng($fname);
$kal = cropAlign($im, $minsz, $minsz, 'center', 'middle');
imagePng($kal, "cropped_" . $fname);
}else{
// For JPEG
$im = imagecreatefromjpeg($fname);
$kal = cropAlign($im, $minsz, $minsz, 'center', 'middle');
imageJpeg($kal, "cropped_" . $fname);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment