Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Last active October 31, 2017 04:49
Show Gist options
  • Save addeeandra/f6d2bb62f9e747ed6615ee7e2c6602b0 to your computer and use it in GitHub Desktop.
Save addeeandra/f6d2bb62f9e747ed6615ee7e2c6602b0 to your computer and use it in GitHub Desktop.
Cropping image on PHP
<?php
# START CROPPING -- it just need 4 lines of code to crop an image
$img = imagecreatefromjpeg('assets/img/myimage.jpg');
$size = min(imagesx($img), imagesy($img));
$img_squared = imagecrop($img, [ 'x' => 0, 'y' => 0, 'width' => $size, 'height' => $size ]);
if ($img_squared !== false) ($img_squared, 'assets/img/myimage-squared.jpg', 80);
# END OF CROPPING -- read the explanation below
# READ MORE here http://php.net/manual/en/function.imagecrop.php
# Okay, first we need to get an image from a path. See http://php.net/manual/en/function.imagecreatefromjpeg.php
# You can use imagecreatefrompng instead for .png formatted image
$img = imagecreatefromjpeg('assets/img/myimage.jpg');
# use $size = min(width, height) instead $size = (width < height) ? width : height
# Got it?
$size = min(imagesx($img), imagesy($img));
# Crop the image! See http://php.net/manual/en/function.imagecrop.php
# Will crop from left top (x=0 y=0 axis) of the image to the given size of width and height
$img_cropped = imagecrop($img, [ 'x' => 0, 'y' => 0, 'width' => $size, 'height' => $size ]);
# if you want to crop the center of it, add some calculation on x,y anchor :
# [
# 'x' => (imagesx($img) - $size) / 2,
# 'y' => (imagesy($img) - $size) / 2,
# ...
# ]
# if successfully cropped, save it somewhere. Btw '80' is the quality, it's optional.
if ($img_cropped !== false) {
imagejpeg($img_cropped, 'assets/img/myimage-squared.jpg', 80);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment