I need to make thumbnails without empty space and in the original ratio. Please help me check this algorithm to improve it.
public function createThumbnail($imagePath, $thumbnailPath, $targetWidth, $targetHeight)
{
list( $originalWidth, $originalHeight, $originalType ) = getimagesize($imagePath);
$targetRatio = $targetWidth / $targetHeight;
$originalRatio = $originalWidth / $originalHeight;
if ( $originalRatio >= $targetRatio ) {
if ( $originalRatio >= 1 ) {
$sourceWidth = $originalHeight * $targetRatio;
$sourceHeight = $originalHeight;
$sourceX = ( $originalWidth - $sourceWidth ) / 2;
$sourceY = 0;
} else {
$sourceWidth = $originalWidth / $originalRatio * $targetRatio;
$sourceHeight = $originalHeight;
$sourceX = ( $originalWidth - $sourceWidth ) / 2;
$sourceY = 0;
}
} else {
if ( $originalRatio >= 1 ) {
$sourceWidth = $originalWidth * $originalRatio / $targetRatio;
$sourceHeight = $originalHeight;
$sourceX = ( $originalWidth - $sourceWidth ) / 2;
$sourceY = 0;
} else {
$sourceWidth = $originalWidth;
$sourceHeight = $originalHeight * $originalRatio / $targetRatio;
$sourceX = 0;
$sourceY = ( $originalHeight - $sourceHeight ) / 2;
}
}
$originalImage = $this->imageCreateFromType( $originalType, $imagePath );
$thumbnailImage = imagecreatetruecolor( $targetWidth, $targetHeight );
imagecopyresampled( $thumbnailImage, $originalImage, 0, 0, $sourceX, $sourceY, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight );
imagepng( $thumbnailImage, $thumbnailPath );
}