How to scale up image into thumbnail without distorting it?

The core problem that you’re running into is that WordPress isn’t actually doing anything to your images, because it doesn’t upscale images. You can use hooks to modify WordPress’ behavior without hacking core, or you can try to fix the issue with CSS.

Changing WordPress to Upscale Thumbnails

ALXMedia has an useful example on adding this behavior. Excerpt below.

// Upscale thumbnails when the source image is smaller than the thumbnail size. Retain the aspect ratio.
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 );

Fixing it with CSS

The issue in CSS is that you have an image that has different proportions compared to it’s container (because it’s not upscaling nor cropping), and you’re setting both the height and width to 100%. What you should instead do is to set one of those dimensions to 100% (the width in this case) and the other to auto. Assuming you want to mimic the crop, you can set the overflow on the parent div to hidden in order to crop it. This will only crop the bottom however, so you’ll need to play around with margins or other positioning tricks to make it appear like a centered crop.

Here’s an example of what the correct css might look like:

.thumbpost{
    width:100%;
    height:320px;
    overflow:hidden;
}

.thumbpost img{
    width:100%;
    height:auto;
}

Leave a Comment