Created
April 27, 2022 11:19
-
-
Save umbalaconmeogia/2f4436c49a5351e0c57d43860c46c503 to your computer and use it in GitHub Desktop.
Compress image file using PHP imagejpeg() function
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 | |
/** | |
* Sample to compress image file in PHP. | |
* | |
* This will compress all files in *input* directory and store the result in *output* directory. | |
* | |
* To run this code, PHP extension *gd* should be enabled. | |
* | |
* Syntax | |
* ```shell | |
* php compressImage.php | |
* ``` | |
*/ | |
// Get files in directory input, ignore '.' and '..'. | |
$files = array_diff(scandir('input'), ['.', '..']); | |
// Convert files to output/small_<input name>.jpeg | |
foreach ($files as $file) { | |
compress("input/$file", "output/small_{$file}.jpeg", 40); | |
} | |
/** | |
* Compress image file to jpeg file. | |
* | |
* The source code is from https://stackoverflow.com/questions/11418594/how-to-reduce-the-image-size-without-losing-quality-in-php/19404938#19404938 | |
* | |
* @param string $source Image file of type jpeg/gif/png | |
* @param string $destination Output image | |
* @param float $quality Ratio to compress image, between 1 to 100. | |
*/ | |
function compress($source, $destination, $quality) | |
{ | |
$info = getimagesize($source); | |
if ($info['mime'] == 'image/jpeg') | |
$image = imagecreatefromjpeg($source); | |
elseif ($info['mime'] == 'image/gif') | |
$image = imagecreatefromgif($source); | |
elseif ($info['mime'] == 'image/png') | |
$image = imagecreatefrompng($source); | |
imagejpeg($image, $destination, $quality); | |
return $destination; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment