Image resizing

Wanting to create a thumbnail makes my wordpress days a lot longer than i would like. Found a nice function about image_resize using an absolute path for cropping images for a slider in the making. I just resized the images to my likings and uploaded my script to a somewhat slower server, and then the problems.

The image resize function uses some server unfriendly functions for resizing. It generally loads the image live and generates all the images created again on each visit. But with no other function, found by me, to on the fly resize images i created a maybe_image_resize function so we can skip the automatic image regeneration.

function maybe_image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {

 // checking the size, or if it even is an image
 $size = @getimagesize( $file );
 if ( !$size )
  return new WP_Error('invalid_image', __('Could not read image size'), $file);
 list($orig_w, $orig_h, $orig_type) = $size;

 // internal image resizer for the dimensions
 $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
 if ( !$dims )
  return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
 list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;

 // cache filename suffix
 if ( !$suffix )
  $suffix = "{$dst_w}x{$dst_h}";

 $info = pathinfo($file);
 $dir = $info['dirname'];
 $ext = $info['extension'];
 $name = wp_basename($file, ".$ext");

 if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
  $dir = $_dest_path;
 $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";

 // checking for file existance
 if(file_exists($destfilename)) {
  // and for filetime comparison
  if(filemtime($destfilename) > filemtime($file)) {
   return $destfilename;
  }
 }
 // no resized file, regenerate
 return image_resize( $file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality );
}

Cloning the image_resize function and checking for sizes and output filetime so we wont create a image when not needed, so the server will just output the images without regenerating them.

I still don`t like the way wordpress generates images. We can generate an image when uploading, but if you want to regenerate it later you have to manually regenerate it. When i inslalled the woocommerce plugin on a site i had to re-upload an image so the sizes would regenerate. So i am not the only one with this workaround. But if i have the time i would like to investigate more so the can be a solution.

Geef een reactie

Jouw e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *