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: 600×500 > Thumbnail: 400×400.
  • #2 Uploaded image: 500×300 > Thumbnail: 400×300.
  • #3 Uploaded image: 300×200 > Thumbnail: 300×200.

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: 600×500 > Thumbnail: 400×400.
  • #2 Uploaded image: 500×300 > Thumbnail: 300×300.
  • #3 Uploaded image: 300×200 > Thumbnail: 200×200.

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.

2

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.

Leave a Comment