About Tinypng
One of the best services for compressing images is https://tinypng.com/. Each month you can compress up to 500 images free. If you need to compress more images each month it costs, but it’s at a low price ($0.009 per image).
Compressing images is good for loading time, better user experience and SEO.
Tinypng compressor plugin - For Kirby
A good thing is that there is an Tinypng API. Another great things is that Kirby now support hooks!
Code
- Save it as /tinypng/tinypng.php in your plugin folder.
- Download http://curl.haxx.se/ca/cacert.pem and put it in the same folder.
- If you DON’T want to overwrite the same file, change the last $input to $output instead.
Here is the code…
<?php
kirby()->hook('panel.file.upload', function( $page ) {
$path = kirby()->roots()->content();
$key = "YOUR API KEY";
$input = $page->dir() . '/' . $page->filename();
$output = $page->dir() . '/' . $page->name() . '-min' . '.' . $page->extension();
tinypng_image_compressor( $key, $input, $input );
});
function tinypng_image_compressor( $key, $input, $output ) {
$request = curl_init();
curl_setopt_array($request, array(
CURLOPT_URL => "https://api.tinify.com/shrink",
CURLOPT_USERPWD => "api:" . $key,
CURLOPT_POSTFIELDS => file_get_contents($input),
CURLOPT_BINARYTRANSFER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_CAINFO => __DIR__ . "/cacert.pem",
CURLOPT_SSL_VERIFYPEER => true
));
$response = curl_exec($request);
if (curl_getinfo($request, CURLINFO_HTTP_CODE) === 201) {
$headers = substr($response, 0, curl_getinfo($request, CURLINFO_HEADER_SIZE));
foreach (explode("\r\n", $headers) as $header) {
if (strtolower(substr($header, 0, 10)) === "location: ") {
$request = curl_init();
curl_setopt_array($request, array(
CURLOPT_URL => substr($header, 10),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CAINFO => __DIR__ . "/cacert.pem",
CURLOPT_SSL_VERIFYPEER => true
));
file_put_contents($output, curl_exec($request));
}
}
} else {
print(curl_error($request));
print("Compression failed");
}
}
Feedback?