Last active
October 15, 2024 05:51
-
-
Save janzikan/2994977 to your computer and use it in GitHub Desktop.
PHP: Resize image - preserve ratio of width and height
This file contains 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
/** | |
* Resize image - preserve ratio of width and height. | |
* @param string $sourceImage path to source JPEG image | |
* @param string $targetImage path to final JPEG image file | |
* @param int $maxWidth maximum width of final image (value 0 - width is optional) | |
* @param int $maxHeight maximum height of final image (value 0 - height is optional) | |
* @param int $quality quality of final image (0-100) | |
* @return bool | |
*/ | |
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80) | |
{ | |
// Obtain image from given source file. | |
if (!$image = @imagecreatefromjpeg($sourceImage)) | |
{ | |
return false; | |
} | |
// Get dimensions of source image. | |
list($origWidth, $origHeight) = getimagesize($sourceImage); | |
if ($maxWidth == 0) | |
{ | |
$maxWidth = $origWidth; | |
} | |
if ($maxHeight == 0) | |
{ | |
$maxHeight = $origHeight; | |
} | |
// Calculate ratio of desired maximum sizes and original sizes. | |
$widthRatio = $maxWidth / $origWidth; | |
$heightRatio = $maxHeight / $origHeight; | |
// Ratio used for calculating new image dimensions. | |
$ratio = min($widthRatio, $heightRatio); | |
// Calculate new image dimensions. | |
$newWidth = (int)$origWidth * $ratio; | |
$newHeight = (int)$origHeight * $ratio; | |
// Create final image with new dimensions. | |
$newImage = imagecreatetruecolor($newWidth, $newHeight); | |
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); | |
imagejpeg($newImage, $targetImage, $quality); | |
// Free up the memory. | |
imagedestroy($image); | |
imagedestroy($newImage); | |
return true; | |
} | |
/** | |
* Example | |
* resizeImage('image.jpg', 'resized.jpg', 200, 200); | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Everything works fine except PNG transparency. I am getting a black background on all PNGs.