Skip to content

Instantly share code, notes, and snippets.

@peterrattew-old
Created March 21, 2017 16:02
Show Gist options
  • Save peterrattew-old/196a8063aab38fcd1b0dd2b21b992fcd to your computer and use it in GitHub Desktop.
Save peterrattew-old/196a8063aab38fcd1b0dd2b21b992fcd to your computer and use it in GitHub Desktop.
On the fly resizing with Wordpress and NGINX
<?php
add_filter('image_downsize', 'custom_image_downsize', 10, 3);
function custom_image_downsize($value = false, $post_id, $size = 'medium') {
global $_wp_additional_image_sizes;
if(is_array($size)) {
$width = (int) @$size[0];
$height = (int) @$size[1];
$crop = (@$size[2]) ? 'c' : '';
}
elseif($img_size = @$_wp_additional_image_sizes[$size]) {
$width = $img_size['width'];
$height = $img_size['height'];
$crop = ($img_size['crop']) ? 'c' : '';
}
elseif(is_string($size)) {
$width = get_option($size.'_size_w');
$height = get_option($size.'_size_h');
$crop = get_option($size.'_crop') ? 'c' : '';
if(!$crop) {
$meta = wp_get_attachment_metadata($post_id);
$full_w = absint(@$meta['width']);
$full_h = absint(@$meta['height']);
if($full_w && $full_w) {
$height = floor($width*($full_h/$full_w));
}
}
}
if(@$width && @$height && $img_url = wp_get_attachment_url($post_id)) {
$parts = pathinfo($img_url);
$img_url = sprintf('%s/%s-%dx%d%s.%s', $parts['dirname'], $parts['filename'], $width, $height, $crop, $parts['extension']);
return array($img_url, $width, $height, false);
}
return false;
}
?>
set $upload_path path/to/uploads;
location ~ "/image/crop/(.*)\.(jpg|jpeg|png|gif)" {
alias $upload_path$1.$2;
image_filter crop $arg_width $arg_height;
image_filter_jpeg_quality 75;
}
location ~ "/image/resize/(.*)\.(jpg|jpeg|png|gif)" {
alias $upload_path$1.$2;
image_filter resize $arg_width $arg_height;
image_filter_jpeg_quality 75;
}
location ~ "/uploads/(.*)-([0-9]+)x([0-9]+)(c)?\.(jpg|jpeg|png|gif)" {
set $crop $4;
set $action resize;
if ($crop = c) { set $action crop; }
set $image_path $1-$2x$3$4.$5;
set $image_uri image/$action/$1.$5?width=$2&height=$3&action=$action;
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:80/$image_uri;
break;
}
proxy_store $upload_root$image_path;
proxy_store_access useR:rw group:rw all:r;
proxy_temp_path /tmp/images;
proxy_set_header Host $host;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment