To get the image derivative URI for an image to which is applied a specific image style, you can use the following code.
// Load the ImageStyle instance in $image_style, for example with
// $image_style = ImageStyle::load($id).
// $image_uri is the path/URI for the image to which the style is applied.
if ($image_style->supportsUri($image_uri)) {
$derivative_uri = $style->buildUri($image_uri);
}
Keep in mind that image derivatives are created only when the URL returned from $image_style->buildURL($image_uri)
is requested (from a browser). Building the URI (or the URL) doesn't generate the derivative image; it returns the URI (URL) for an image that couldn't exist, yet.
To check an image derivative could be created, code similar to the one used from ImageStyleDownloadController::deliver()
should be used.
if ($image_style->supportsUri($image_uri)) {
$derivative_uri = $style->buildUri($image_uri);
if (!file_exists($image_uri)) {
$path_info = pathinfo($image_uri);
$converted_image_uri = $path_info['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'];
if (file_exists($converted_image_uri)) {
$image_uri = $converted_image_uri;
}
}
$success = file_exists($derivative_uri) || $image_style->createDerivative($image_uri, $derivative_uri);
if ($success) {
$image = Drupal::service('image.factory')->get($derivative_uri);
$uri = $image->getSource();
}
}