Skip to content

Pre generate custom size derivatives

Thomas Kuther edited this page Dec 26, 2018 · 4 revisions

If your server is low on precessing power, you can pre-generate derivatives. Unfortunately the default batch manager action for this does not work for custom size derivates which are used by Bootstrap Default/Darkroom's default thumbnail grid and also plugins like gdThumb and GThumb+.

You can use following plugin. It will add a new batch manager action called "Pre-generate custom size derivatives".

In Admin -> Plugins -> LocalFiles Editor -> Personal Plugin Tab, add following somewhere between the <?php ... ?>:

add_event_handler('loc_end_element_set_global', 'bm_gen_custom_derivatives_form');
add_event_handler('element_set_global_action', 'bm_gen_custom_derivatives_action', EVENT_HANDLER_PRIORITY_NEUTRAL, 2);

function bm_gen_custom_derivatives_form() {
  global $template;
  $template_add = '';
  foreach (array_keys(ImageStdParams::$custom) as $custom) {
    $template_add = $template_add . '<input type="checkbox" name="custom_sizes[]" value="' . $custom . '">' . $custom . '<br />';
  }
  
  $template->append('element_set_global_plugins_actions', array(
     'ID' => 'GenCustomDerivatives', 
     'NAME' => l10n('Pre-cache custom size derivatives'), 
     'CONTENT' => $template_add,
  ));
}

function bm_gen_custom_derivatives_action($action, $collection) {
  if ($action == 'GenCustomDerivatives'){
    global $page;
    foreach ($collection as $image_id){
      if (isset($_POST['custom_sizes'])) {
        $strCookie = 'pwg_id=' . $_COOKIE['pwg_id'] . '; path=/';
        $ch = curl_init(get_absolute_root_url() .'ws.php?format=json&method=pwg.images.getInfo&image_id=' . $image_id);
        curl_setopt($ch, CURLOPT_REFERER, get_absolute_root_url());
        curl_setopt($ch, CURLOPT_COOKIE, $strCookie );
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = json_decode(curl_exec($ch));
        $sq_url = $result->result->derivatives->square->url;
        
        foreach ($_POST['custom_sizes'] as $size) {
          $url = str_replace('sq.jpg', 'cu_' . $size . '.jpg', $sq_url);
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_exec($ch);
        }
        curl_close($ch);
      }
    }
  }
}

Note: this one requires php curl support.

Clone this wiki locally