Drupal 8 Smart Image Style - Handle aspect ratio for small and long images

April 18, 2020

Problem Statement

I’ve been using image styles, and heavily used “Scale and crop” style, which worked for me in almost 95% of the cases. Recently, I’ve been getting images which are like horizontally long or vertically long. Default image styles could not work for any of combination.

Below is one example image, and its result (Prior to my solution)

Original Image

Drupal Image Style

Poor Result

Drupal Image Style

Lets take a look at how I solve this problem.

Solution to Correctly styling images

I found the two hero modules:

After installing them, Please follow the steps:

  1. Goto /admin/config/media/crop, and create a new crop type

Drupal Image Style

In aspect ratio: put 16:9, or you can put your desired one. Leave rest of the field as it is. Save it.

  1. Goto /admin/config/media/image-styles and create a new image style
  2. Add a new effect: Manual Crop, select your crop type you created in above step.
  3. Add another effect: Scale, and put following:
  • Height = 500. You can give your desired height
  • Leave width field as it is.
  • Uncheck Allow Upscaling

Scaling effect configuration

Drupal Image Style

Final Manual Crop configuration

Drupal Image Style

  1. Goto your content type, and click on Manage Display and select your style you created in above step.

Drupal Image Style

Now, see your content. It should work as expected.

Note

You might have doubt for above 2nd effect (Scaling) in image style. If you leave that image style with only Manual Crop effect. Your images might display in expected size. I encountered a case where image was vertically long. For that, I had to put a scaling configuration as well. And if you noted I did not specify the width. It will automatically maintain aspect ratio. And, the max height for all images will be the value I specified.

Result

See the results:

For Horizontally long image

This example image I have put on top.

Original Image

Drupal Image Style

After manual crop configuration

Drupal Image Style

For vertically long image

Original Image

Drupal Image Style

After manual crop configuration

Drupal Image Style

Let me know if you have any doubts in comments.


Similar Posts

Latest Posts