Drupal 8图像与图像样式

use*_*914 22 drupal image drupal-8

在drupal 7中,我使用函数image_style_url('style', uri)生成带有样式的新图像并返回图像的路径.那么在drupal 8中会有什么而不​​是它呢?谢谢

Cli*_*ive 54

根据变更记录:

use Drupal\image\Entity\ImageStyle;

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

  • @FredK你错误地看着它:你没有_need_在模板中这样做; 你可能想要出于任何原因,但这是一个坏主意,你绝对不需要_need_.模板预处理功能是此代码的正确位置.但是如果你坚持认为它必须在Twig中完成,你需要编写一些PHP来向它公开`ImageStyle`类方法.不过,这需要的时间比推荐的方式要长 (3认同)

sag*_*ons 14

您应尽可能尝试使用新的Drupal功能.

相反,使用:

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());
Run Code Online (Sandbox Code Playgroud)

根据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);
Run Code Online (Sandbox Code Playgroud)


Yus*_*sef 6

在您的控制器和Drupal的其他OOP部分中,您可以使用:

use Drupal\image\Entity\ImageStyle;

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

YOUR_THEME.theme文件中Error: Class 'ImageStyle' not found in YOURTHEMENAME_preprocess_node你可以用下面的文件来完成

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

另一种方法是提供一个可渲染的数组,让drupal Render引擎渲染它.

$render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => $path,
    // optional parameters
];
Run Code Online (Sandbox Code Playgroud)