27

In drupal 7, i use function image_style_url('style', uri) to generate new image with style and return image's path. so what will be instead of it in drupal 8? thanks

pavel
  • 26,538
  • 10
  • 45
  • 61
user3810914
  • 425
  • 2
  • 5
  • 9

7 Answers7

63

Per the change records:

use Drupal\image\Entity\ImageStyle;

$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);
Clive
  • 36,918
  • 8
  • 87
  • 113
  • 1
    I need to do this inside a Twig template but here I can't use PHP. How can I do? – Fred K Apr 22 '16 at 15:28
  • 3
    @FredK You're looking at that wrongly: you don't _need_ to do it in a template; you might want to for whatever reason, but it's a bad idea, and you definitely don't _need_ to. A template preprocess function is the right place for this code. But if you're adamant that it has to be done in Twig, you'll need to write some PHP to expose the `ImageStyle` class methods to it. That'll take longer than just doing it the recommended way, though – Clive Apr 22 '16 at 15:31
  • 1
    For anyone still looking for the solution @FredK was, the [Twig Tweak](https://www.drupal.org/project/twig_tweak) module has an `image_style` filter that can be used to avoid preprocessing – Clive Mar 01 '19 at 19:23
18

You should try to use the new Drupal functions wherever possible.

Instead, use:

use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

$fid = 123;
$file = File::load($fid);
$image_uri = ImageStyle::load('your_style-name')->buildUrl($file->getFileUri());

Edited as per https://www.drupal.org/node/2050669:

$original_image = 'public://images/image.jpg';

// Load the image style configuration entity
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('thumbnail');

$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);
sagesolutions
  • 491
  • 4
  • 9
9

In your Controllers and other OOP part of Drupal you can use :

use Drupal\image\Entity\ImageStyle;

$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);

And in YOUR_THEME.theme file while Error: Class 'ImageStyle' not found in YOURTHEMENAME_preprocess_node you can do it with the follwing

 $path = 'public://images/image.jpg';
 $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
 $url = $style->buildUrl($path);

Another method is provide a renderable array and let the drupal Render engine render it.

$render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => $path,
    // optional parameters
];
Yuseferi
  • 7,931
  • 11
  • 67
  • 103
2

I have found that I often want to preprocess the image to apply an image style to an image on a node or a paragraph type. In many cases I have created a paragraph that allows the user to choose the width of the image as a percentage. In the preprocess I would check the value of the width and apply the correct image style.

use Drupal\image\Entity\ImageStyle;

function THEME_preprocess_paragraph__basic_content(&$vars) {
  //get the paragraph
  $paragraph = $vars['paragraph'];

  //get the image
  $images = $paragraph->get('field_para_image');
  //get the images value, in my case I only have one required image, but if you have unlimited image, you could loop thru $images
  $uri = $images[0]->entity->uri->value;

  //This is my field that determines the width the user wants for the image and is used to determine the image style
  $preset = $paragraph->get('field_column_width')->value;

  $properties = array();
  $properties['title'] = $images[0]->getValue()['title'];
  $properties['alt'] = $images[0]->getValue()['alt'];

  //this is where the Image style is applied
  switch($preset) {
     case 'image-20':
       $properties['uri'] = ImageStyle::load('width_20_percent')->buildUrl($uri);
       break;
     case 'image-45':
       $properties['uri'] = ImageStyle::load('width_45_percent')->buildUrl($uri);
       break;
     case 'image-55':
       $properties['uri'] = ImageStyle::load('width_55_percent')->buildUrl($uri);
       break;
     case 'image-100':
       $properties['uri'] = ImageStyle::load('width_100_percent')->buildUrl($uri);
       break;
  }
  //assign to a variable that the twig template can use
  $vars['basic_image_display'] = $properties;
}

In this example, I am preprocessing a specific paragraph type named "basic_content" but you can do the same thing with a node preprocess. Continuing my example, I would have a twig template named paragraph--basic_content.html.twig to handle the display of that paragraph type.

Displaying the image would be something like this in the twig file.

<img class="img-responsive" src="{{basic_image_display['uri']}}" alt="{{ basic_image_display['alt'] }}" title="{{ basic_image_display['title'] }}"/>
1
$view_mode = $variables['content']['field_media_image']['0']['#view_mode'];
$display_content = \Drupal::service('entity_display.repository')
->getViewDisplay('media', 'image', $view_mode)->build($media_entity);
$style = ImageStyle::load($display_content['image'][0]['#image_style']); $original_image = $media_entity->get('image')->entity->getFileUri();
$destination = $style->buildUri($original_image);

This is how you get image style from a media image entity.

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
muri
  • 11
  • 2
  • Are you assuming this code goes in a specific hook_preprocess function? E.g. where does $media_entity come from for ```->build($media_entity)``` ? – JDev518 Feb 25 '22 at 18:16
0

Works for me from a classic Drupal database Query in .module file :

$query = \Drupal::database()->select('file_managed', 'f' );
$query->addField('f', 'uri');
$pictures = $query->execute()->fetchAll();

foreach ($pictures as $key => $picture) {

   $largePictureUri = entity_load('image_style', 'large')->buildUrl($picture->uri);
}
-1

I used in Drupal 8 this code. It's working fine.

$fid = 374; //get your file id, this value just for example 
$fname = db_select('file_managed', 'f')->fields('f', array('filename'))->condition('f.fid', $fid)->execute()->fetchField();
$url = entity_load('image_style', 'YOUR_STYLE_NAME')->buildUrl($fname);
Undrrey
  • 15
  • 2
  • 1
    It's best practice (and cleaner code) to use the Drupal objects instead of database queries. I would recommend the `$file = File::load($fid);` command to get the File object instead of querying the database for the filename. – sagesolutions Jul 27 '16 at 15:26
  • 1
    To add to sagesolution's comment, the entity_load() function is now deprecated so users should refer to the answers that load the style using the ImageStyle class. – Sean Wickham Jan 26 '17 at 16:59