Thursday, 14 September 2017

Reduce Image Size To 10KB Using PHP code

//Copy this function in App Controller in cakePHP
public function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80)
{
// Obtain image from given source file.
/* if (!$image = @imagecreatefromjpeg($sourceImage))
{
return false;
} */
$info = getimagesize($sourceImage);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($sourceImage);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($sourceImage);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($sourceImage);
// 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;
}

//calling function like this
$url = 'http://'.$_SERVER['HTTP_HOST']. $this->base.$images['image_path'];
$fileNmaeArray = array();
$fileNmaeArray = explode('.',$images['image_path']);
$image_name = $fileNmaeArray[0];
$image_ext = $fileNmaeArray[1];
$url1 = WWW_ROOT.$image_name.'_compressed.'.$image_ext;
$this->resizeImage($url, $url1, 2000, 2000 , 50);

No comments:

Post a Comment