Created
August 31, 2012 21:30
-
-
Save thefotolander/3559349 to your computer and use it in GitHub Desktop.
PHP function to generate sizes or crop images
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 /** Generate a cropped version of gif, png or jpg images */ | |
public function poifox_generateSize( $imagepath, $destWidth = 80, $cropSquare = true, $cropThreshold = 400 ) { | |
// get original image size | |
list($width, $height) = getimagesize($imagepath); | |
// Always crop thumbs smaller than $cropThreshold | |
$cropSquare = ($destWidth < $cropThreshold || $cropSquare ); | |
// Upscaling sucks | |
$destWidth = ( $destWidth < $width ) ? $destWidth : $width ; | |
// The aspect ratio of the image | |
$ratio = $width / $height; | |
// offset defines where the coordinates on the original image | |
// where the cropping are starts, defaults to 0 for non cropping | |
$offsetX = 0; | |
$offsetY = 0; | |
// treats height as non cropping | |
$destHeight = ceil($destWidth / $ratio); | |
// the original image is cropped up to this coordinate | |
$sourceWidth = $width; | |
$sourceHeight = $height; | |
// Is the image square? | |
$isSquare = ( $width == $height ); | |
// you asked for cropping and the image is not square | |
// if image is square we don't even bother on calculating this | |
if ( $cropSquare && ! $isSquare ) { | |
$destHeight = $destWidth; | |
if ( $width > $height ) { // LANDSCAPE | |
$offsetX = ( $width - $height ) / 2; // X offset rules | |
$sourceWidth = $sourceHeight = $height; // Adjust source to height | |
} elseif ( $width < $height ) { // PORTRAIT | |
$offsetY = ( $height - $width ) / 2; // Y offset rules | |
$sourceWidth = $sourceHeight = $width; // adjust source to width | |
} | |
} | |
$originalImage = imagecreatefromstring(file_get_contents($imagepath)); | |
$resultImage = imagecreatetruecolor($destWidth, $destHeight); | |
// Copy pixels | |
imagecopyresampled( | |
$resultImage, $originalImage, | |
0,0, // Destiny offset | |
$offsetX, $offsetY, // Origin Offset | |
$destWidth, $destHeight, // Destiny Size | |
$sourceWidth, $sourceHeight // Origin cropping | |
); | |
// free memory taken by the original image | |
imagedestroy($originalImage); | |
// Returns image resource | |
// You must take care of saving the image outside of this function | |
return $resultImage; | |
} ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment