Thumbnail upscale & correct crop in WordPress

Go to source

By default, the WordPress custom thumbnail size functionality hard-crops large source images into smaller ones perfectly well. However, you will run into size issues when the source image is smaller than the custom thumbnail size.

It can be fixed by adding this code to your theme’s functions.php file. It upscales images to fit all thumbnail sizes and crops them correctly.

/*  Thumbnail upscale
/* ------------------------------------ */	
function alx_thumbnail_upscale( $default, $orig_w, $orig_h, $new_w, $new_h, $crop ){
	if ( !$crop ) return null; // let the wordpress default function handle this

	$aspect_ratio = $orig_w / $orig_h;
	$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);

	$crop_w = round($new_w / $size_ratio);
	$crop_h = round($new_h / $size_ratio);

	$s_x = floor( ($orig_w - $crop_w) / 2 );
	$s_y = floor( ($orig_h - $crop_h) / 2 );

	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
add_filter( 'image_resize_dimensions', 'alx_thumbnail_upscale', 10, 6 );

The slight downside (not much to worry about with the server space we have today) is that if you for example upload a 16×16 favicon to your media library, it will be cropped and upscaled to all larger thumbnail sizes available. So, some more images will be created.