How to scale up image into thumbnail without distorting it?

I have a section in my single post page that contains the post thumbnail. When using a smaller image as featured image (smaller than the thumbnail size, in width or height) it gets distorted to fill the thumbnail and lose its proportion. When the featured image is bigger than the thumbnail size or at least has a similar proportion, it seems to work just fine.

An image showing the case: http://i.imgur.com/XtdpuyV.jpg

Here's all the code I used:

add_image_size( 'thumbpost', 698, 320, true );

div class="thumbpost"?php { the_post_thumbnail('thumbpost' ); } ?/div

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

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

Wordpress generates an image maintaining the original width, that is smaller than the thumbnail's width that I want

Topic post-thumbnails scale Wordpress

Category Web


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;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.