Created
October 29, 2018 17:55
-
-
Save matthew-inamdar/30fe14a0a8b3f4913ea9ecf8ca025cbc to your computer and use it in GitHub Desktop.
A function to crop an image from the center (1:1) and resize it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param string $content | |
* @param int $width | |
* @param int $height | |
* @return string | |
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException | |
*/ | |
function crop_and_resize(string $content, int $width, int $height): string | |
{ | |
// Store the contents into a temporary file. | |
$sourceId = uuid(); | |
\Illuminate\Support\Facades\Storage::disk('temp')->put($sourceId, $content); | |
$sourcePath = storage_path("temp/$sourceId"); | |
// Create a GD instance from the temporary file and a new file. | |
$source = imagecreatefromjpeg($sourcePath); | |
$destination = imagecreatetruecolor($width, $height); | |
// Get the width and height from the source image. | |
list($sourceWidth, $sourceHeight) = getimagesize($sourcePath); | |
// Get the top left crop coordinates for the source image. | |
if ($sourceWidth >= $sourceHeight) { | |
$sourceX = floor(($sourceWidth - $sourceHeight) / 2); | |
$sourceY = 0; | |
} else { | |
$sourceX = 0; | |
$sourceY = floor(($sourceHeight - $sourceWidth) / 2); | |
} | |
// Get the cropped width and height for the source image. | |
$croppedWidth = min($sourceWidth, $sourceHeight); | |
$croppedHeight = $croppedWidth; | |
imagecopyresampled( | |
$destination, | |
$source, | |
0, | |
0, | |
$sourceX, | |
$sourceY, | |
$width, | |
$height, | |
$croppedWidth, | |
$croppedHeight | |
); | |
// Get the contents of the destination file. | |
$destinationId = uuid(); | |
$destinationPath = storage_path("temp/$destinationId"); | |
imagejpeg($destination, $destinationPath, 80); | |
$destinationContent = \Illuminate\Support\Facades\Storage::disk('temp')->get($destinationId); | |
// Delete the temporary files. | |
\Illuminate\Support\Facades\Storage::disk('temp')->delete($sourceId); | |
\Illuminate\Support\Facades\Storage::disk('temp')->delete($destinationId); | |
return $destinationContent; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment