Programmatically Applying Image Styles in Drupal 9 with the ImageStyle Class

Drupal 9 offers powerful tools for managing and manipulating images, and Image Styles are at the core of this functionality. In this blog post, we'll dive into the process of programmatically applying an image style using the ImageStyle class. Specifically, we'll work with the "inmate_profile_pic" image style to demonstrate how you can dynamically control image display on your Drupal website.

Using the ImageStyle Class

The ImageStyle class in Drupal 9 provides an object-oriented way to work with image styles. Here's how to load and apply an image style programmatically:

Step 1: Load the Image Entity

Before applying an image style, you need to load the image entity you want to work with. You can do this using Drupal's Entity API or other relevant methods:

phpCopy code

// Load the image entity (example).
$image = \Drupal\file\Entity\File::load($image_fid);

Step 2: Load the Image Style

Load the desired image style using the ImageStyle class. In this case, we're loading the "inmate_profile_pic" image style:

// Load the "inmate_profile_pic" image style.
$image_style = \Drupal\image\Entity\ImageStyle::load('inmate_profile_pic');

Step 3: Apply the Image Style

Now that you have the image entity and the image style loaded, you can apply the style to the image using the derivativeUri() method:

// Apply the "inmate_profile_pic" image style to the image.
$derivative_uri = $image_style->buildUri($image->getFileUri());

Step 4: Display the Image with the Applied Image Style

With the image style applied, you can now use the generated derivative URI to display the image in your code:

// Display the image with the applied "inmate_profile_pic" image style.
$output = '<img src="' . file_url_transform_relative(file_create_url($derivative_uri)) . '" alt="Profile Picture">';

Conclusion:

By using the ImageStyle class in Drupal 9, you have the flexibility to programmatically apply image styles to your images, making it possible to create dynamic and custom image processing logic. Whether you're building a complex content-driven website or crafting unique visual experiences, this approach empowers you to have precise control over how images are displayed, ensuring a seamless and tailored experience for your site visitors.

With this approach, you can enhance the image display on your Drupal website with confidence and precision.

Share on social media

Add new comment