Created
April 27, 2022 11:21
-
-
Save umbalaconmeogia/4c8b08fe7f6b894242e3337a7320194c to your computer and use it in GitHub Desktop.
Compress image file to specified filesize using PHP ImageMagick
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 *imagemagick* should be enabled. | |
* | |
* Syntax | |
* ```shell | |
* php compressIMagick.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", '500kb'); | |
} | |
/** | |
* Compress image file to jpeg file. | |
* | |
* @param string $source Image file of type jpeg/gif/png | |
* @param string $destination Output image | |
* @param string $fileSize File size to be converted. Default to 500kb | |
*/ | |
function compress($source, $destination, $fileSize = '500kb') | |
{ | |
$im = new IMagick($source); | |
$im->setOption('jpeg:extent', $fileSize); | |
$im->writeImage($destination); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment