Friday, October 25, 2019

How to programmatically Drupal 78 images with image style 2



Drupal 7
In drupal 7, i use function image_style_url('style', uri) to generate new image with style and return image's path.

$path = 'public://images/image.jpg';
$style= 'custom_smallimage';
$derivative_uri = image_style_url($style, $path);
$uri_file_path = file_create_url($derivative_uri);

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

Flexible image style system

Find a derivative URI and URL

D7

$original_image = 'public://images/image.jpg';
$uri = image_style_path('thumbnail', $original_image);
$url = image_style_url('thumbnail', $original_image);

D8

$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);

  Create a derivative image programmatically

D7

$original_image = 'public://images/image.jpg';
$destination = image_style_path('thumbnail', $original_image);
image_style_create_derivative('thumbnail', $original_image, $destination);

D8

$original_image = 'public://images/image.jpg';
// Load the image style configuration entity.
$style = ImageStyle::load('thumbnail');
$destination = $style->buildUri($original_image);
$style->createDerivative($original_image, $destination);



No comments:

Post a Comment

If you have any problem please let me know.