Created
November 6, 2013 14:08
-
-
Save nicklasos/7336604 to your computer and use it in GitHub Desktop.
Reduce image by factor
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
<?php | |
/** | |
* Reduce image by factor | |
* | |
* @param string $originalFile file path | |
* @param string $destinationFile file path | |
* @param int $factor | |
* @return bool | |
*/ | |
private function resizeImageByFactor($originalFile, $destinationFile, $factor = 2) | |
{ | |
// Get width and height of original image | |
$imageData = getimagesize($originalFile); | |
if (!$imageData) { | |
return false; | |
} | |
$originalWidth = $imageData[0]; | |
$originalHeight = $imageData[1]; | |
$newHeight = round($originalHeight / $factor); | |
$newWidth = round($originalWidth / $factor); | |
// Load the image | |
if ($imageData['mime'] === 'image/png') { | |
$imageType = 'png'; | |
$originalImage = imagecreatefrompng($originalFile); | |
} | |
if ($imageData['mime'] === 'image/jpg' || $imageData['mime'] === 'image/jpeg') { | |
$imageType = 'jpg'; | |
$originalImage = imagecreatefromjpeg($originalFile); | |
} | |
if ($imageData['mime'] === 'image/gif') { | |
$imageType = 'gif'; | |
$originalImage = imagecreatefromgif($originalFile); | |
} | |
if (!isset($originalImage, $imageType)) { | |
return false; | |
} | |
$smallerImage = imagecreatetruecolor($newWidth, $newHeight); | |
$squareImage = imagecreatetruecolor($newWidth, $newHeight); | |
// Save alpha! | |
imagealphablending($squareImage, false); | |
imagesavealpha($squareImage, true); | |
$transparent = imagecolorallocatealpha($squareImage, 255, 255, 255, 127); | |
imagefilledrectangle($squareImage, 0, 0, $newWidth, $newHeight, $transparent); | |
imagealphablending($smallerImage, false); | |
imagesavealpha($smallerImage, true); | |
$transparent = imagecolorallocatealpha($smallerImage, 255, 255, 255, 127); | |
imagefilledrectangle($smallerImage, 0, 0, $newWidth, $newHeight, $transparent); | |
imagecopyresampled($smallerImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight); | |
// Copy Image | |
imagecopyresampled($squareImage, $smallerImage, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight); | |
// Save the smaller image FILE if destination file given | |
if($imageType === "jpg") { | |
imagejpeg($squareImage, $destinationFile, 100); | |
} | |
if($imageType === 'gif') { | |
imagegif($squareImage, $destinationFile); | |
} | |
if($imageType === 'png') { | |
imagepng($squareImage, $destinationFile, 9); | |
} | |
imagedestroy($originalImage); | |
imagedestroy($smallerImage); | |
imagedestroy($squareImage); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment