You are here

function imageapi_optimize_services_tinypng in Image Optimize (or ImageAPI Optimize) 7

tinypng ImageAPI Optimize service callback.

File

services/tinypng.inc, line 74
tinypng API service integration.

Code

function imageapi_optimize_services_tinypng($image, $dst) {

  // Gracefully delegate to Image Toolkit if format is not PNG or JPEG.
  if (!in_array($image->info['mime_type'], array(
    'image/png',
    'image/jpeg',
  ))) {
    return FALSE;
  }
  $filepath = drupal_realpath($dst);
  $url = 'https://api.tinypng.com/shrink';
  $settings = variable_get('imageapi_optimize_tinypng');
  $options = array(
    'data' => file_get_contents($filepath),
    'headers' => array(
      'Authorization' => 'Basic ' . base64_encode("api:" . $settings['api_key']),
    ),
    'method' => 'POST',
  );
  $response = drupal_http_request($url, $options);
  $json = drupal_json_decode($response->data);
  if ($response->code == 201) {

    // Compression was successful, retrieve output
    $result = drupal_http_request($json['output']['url']);
    if (!isset($result->error)) {
      if (!file_unmanaged_save_data($result->data, $dst, FILE_EXISTS_REPLACE)) {
        watchdog('imageapi', 'Processed image received from TinyPNG.com could not be saved to disk on @dir. Please review the directory permissions', array(
          '@dir' => $filepath,
        ));
        return FALSE;
      }
      if ($settings['debug_mode_tinypng']) {
        watchdog('imageapi', 'Sucessful request to TinyPNG.com for @file.<br>Initial file size = @input bytes.<br>Final file size = @output bytes.<br>Compression ratio = @ratio.', array(
          '@file' => $dst,
          '@input' => $json['input']['size'],
          '@output' => $json['output']['size'],
          '@ratio' => $json['output']['ratio'],
        ));
      }
      return TRUE;
    }
  }

  // Something went wrong :(
  watchdog('imageapi', 'TinyPNG.com could not process your request for @file. Error code = @error - @msg', array(
    '@file' => $filepath,
    '@error' => $json['error'],
    '@msg' => $json['message'],
  ));
  return FALSE;
}