All of these examples should be immediately runnable in your language of choice. If you don't see your language feel free to contribute an example.
# Optimising a JPG file (e.g. filename.jpg -> optimised.jpg) curl -X POST -s --form "input=@filename.jpg;type=image/jpg" https://www.toptal.com/developers/jpgoptimiser/optimise > optimised.jpg
// core var fs = require('fs'); // from npm var superagent = require('superagent'); // open the output file var outStream = fs.createWriteStream('optimised.jpg'); // do the request var req = superagent .post('https://www.toptal.com/developers/jpgoptimiser/optimise') .attach('input', 'filename.jpg') ; // save the returned file req.end(function(res) { res.pipe(outStream); });
Many thanks to Arjan Haverkamp for this example and Kevin Op den Kamp for an update.
function JPGoptimiser($JPGfile, &$error = '') { $ch = curl_init('https://www.toptal.com/developers/jpgoptimiser/optimise'); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, [ 'input' => new CurlFile($JPGfile, 'image/jpg', $JPGfile) ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $jpg = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status !== 200) { $error = "www.toptal.com request failed: HTTP code {$status}"; return false; } $curl_error = curl_error($ch); if (!empty($curl_error)) { $error = "www.toptal.com request failed: CURL error ${$curl_error}"; return false; } curl_close($ch); return $jpg; } $result = Jpgoptimiser('input.jpg', $error); if (false === $result) { die("{$error}\n"); } file_put_contents('optimised.jpg', $result);
(Ends)