Custom image size / thumbnail - Crop to aspect ratio even when source image is smaller than set dimensions

Normally when you set a custom image size using hard crop - e.g. add_image_size( 'custom-size', 400, 400, true ); - you get the following results:

  • #1 Uploaded image: 600x500 > Thumbnail: 400x400.
  • #2 Uploaded image: 500x300 > Thumbnail: 400x300.
  • #3 Uploaded image: 300x200 > Thumbnail: 300x200.

However what I'd like to do is when the uploaded image is smaller than the set width, or height, or both, of the custom image size, e.g. examples #2 #3 above - instead of the image just being cropped to fit within those dimensions - it's also cropped to match their aspect ratio (which in this case is 1:1) like so:

  • #1 Uploaded image: 600x500 > Thumbnail: 400x400.
  • #2 Uploaded image: 500x300 > Thumbnail: 300x300.
  • #3 Uploaded image: 300x200 > Thumbnail: 200x200.

I don't believe this is possible using the standard add_image_size options, but is it possible using a different function, or hook that modifies the add_image_size function?

Or is there a plugin that adds this functionality?

Any information anyone can provide would be greatly appreciated.

Topic cropping images Wordpress

Category Web


This isn't a really good solution since it's a newer CSS solution and it's only working in 78.9% of users browsers, but there are a few polyfills that can overcome that object-fit-images and fitie

img {
    display: block;
    overflow: hidden;
    width: 400px;
    height: 400px;
    -o-object-fit: cover;
       object-fit: cover;
}

Ideally it would be better if the smaller images scaled proportionally on upload, but I haven't been able to figure out a solution for that.


You're right that it just doesn't work like that.

If it's OK to think of your question the other way around though, you can get the right outcome in modern browsers using a selection of image sizes and responsive images.

If you use code like this:

add_image_size( 'custom-size-small', 200, 200, true );
add_image_size( 'custom-size-medium', 300, 300, true );
add_image_size( 'custom-size-large', 400, 400, true );

... and in your templates something like:

wp_get_attachment_image( $image_ID, 'custom-size-small' )

... then by default (WP 4.4 and later) you will get an image tag with the smallest version from your set as the src and the larger sizes in the srcset attribute, which newer browsers will pick from and display the largest appropriate version.

So then, if a particular image doesn't have a larger version, it doesn't matter. An image that is 300x200 will have a 200x200 version made, that version will be the only one in the HTML and all browsers will show it.

I worked this out while tweaking responsive images so that I get good performance on browsers that only support src and not srcset.

About

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