Is it possible to convert the image format of uploaded images?
My client has uploaded a lot of .png
files, and it would be more bandwidth-friendly to serve them as .jpg
instead.
I already use the thumb() method to display most images on the site to control resolution and file size. I imagine something like this:
thumb($img, array('convert' => 'jpg', 'quality' => 70))
Any suggestions?
You can override the default ImageMagick and/or GD driver as described here . Then you can add custom stuff as you like.
Iβm doing this with my Focus plugin , too:
<?php
/**
* Overriding default GDLib Driver
*/
thumb::$drivers['gd'] = function($thumb) {
try {
$img = new abeautifulsite\SimpleImage($thumb->root());
$img->quality = $thumb->options['quality'];
if (isset($thumb->options['focus']) && isset($thumb->options['fit']) && isset($thumb->options['ratio']) && isset($thumb->options['focusX']) && isset($thumb->options['focusY'])) {
// calculate crop coordinates and width/height for the original image
$focusCropValues = focus::cropValues($thumb);
// crop original image with thumb ratio and resize it to thumb dimensions
$img->crop($focusCropValues['x1'], $focusCropValues['y1'], $focusCropValues['x2'], $focusCropValues['y2'])->thumbnail($thumb->options['width'], $thumb->options['height']);
}
else if ($thumb->options['crop']) {
@$img->thumbnail($thumb->options['width'], $thumb->options['height']);
}
You still need to figure out how to convert the images. I found these to links, but didnβt check if it works:
http://www.imagemagick.org/discourse-server/viewtopic.php?t=24048#p103330
php, png, jpeg
Overriding the driver might cause some conflict with other plugins, e.g. the Focus plugin. But you can actually override the filename, as both the GD driver as the ImageMagick driver will chose the image format based on the thumb fileβs target file (See filename()
method in /kirby/kirby/component/thumb.php
). You should be able to override the output format by setting the filename option on a thumb:
$page->image()->thumb(['width' => 300, 'filename' => '{safeName}-{width}x{height}-{options}.jpg']);
Hope, this helps you to achieve the desired result.
2 Likes