Skip to content

Instantly share code, notes, and snippets.

@nicklasos
Created November 6, 2013 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklasos/7336604 to your computer and use it in GitHub Desktop.
Save nicklasos/7336604 to your computer and use it in GitHub Desktop.
Reduce image by factor
<?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