You can test the quality loss using the PHP GD
and see if it fits, you can also do this procedure while uploading the image:
function compressImage($source_path, $destination_path, $quality) {
$info = getimagesize($source_path);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source_path);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source_path);
}
imagejpeg($image, $destination_path, $quality);
return $destination_path;
}
Explaining the functions used:
getimagesize()
: returns image information (type, size, dimensions, etc.), we use to get the original image MIME Type.
imagecreatefromjpeg()
: creates a new image from the original image.
imagejpeg()
: sends an image to the browser or to a file, this is where the lightest image is created.
Finally the function returns the path of the lightest image.
Example of use: $img = compressImage("images/praia.jpg", "images/compressed/compressed_praia.jpg", 6);
First thank you for answering. I have a question, in case, when lower the value of #quality Do I have the size of the image or less quality? I didn’t quite understand what the code itself does. For example, this imagecreatefromjpeg would create a "lighter image"?
– Igor
This, the lower the value of
$quality
worse will be its quality, the default is +- 7.5. I edited the answer with the explanation of the functions used. The functionimagecreatefromjpeg /png
creates the image identifier, not the image itself, it is actually created with the functionimagejpeg()
, it is important to emphasize that the generated image will always be with the format.jpeg
.– Eduardo Silva
Thank you for answering, @Eduardosilva, but I’ll stick to the Imagick() alternative, which in my case seems more viable. Thank you!
– Igor
I like the solution because it uses a lib that usually comes in PHP. Image Magik may even have more resources, but none of them will help the problem in question.
– Bacco
Is it@Bacco? I’ll look between the two and comment here which was better...
– Igor
@Igor both serve to resize images, and both have a quality setting when saving, so I usually give preference to GD in my projects. But it’s good you know them both, for when you need them for other uses.
– Bacco
It really, really in this case what suits me is GD. Thank you! D
– Igor
To complement the @Eduardosilva response here explains how to remove EXIF headers from the image with GD.
– fernandosavio
And what are these EXIF headers, @fernandosavio? Does it make a difference to remove them or not?
– Igor
EXIF are data on the camera and other metadata that are interesting to save with the original image, but to use on the web image optimizers usually take them out of the image to decrease the size of the image.
– fernandosavio