I'll expand a bit on what acrosman answered, only because I needed this exact same thing so hopefully this will help the next person who comes across this.
I'm working from preprocess_page and using a view to grab my images.
Like his answer make sure you add the ImageStyle:
use Drupal\image\Entity\ImageStyle;
Once I grabbed the view entity I was able to narrow down my image field and then work my way to the styled image.
$image = $entity->get('field_images')->getValue();
$image_entity = File::load($image[0]['target_id']);
$image_uri = $image_entity->get('uri')->value;
$style = ImageStyle::load('my_image_style');
$image_url = $style->buildUrl($image_uri);
So overall my whole function to grab the image from a View and apply a custom image style looked like.
function _mytheme_preprocess_page_front_projects(array &$variables) {
$projects = array();
$view = Views::getView('projects');
if (is_object($view)) {
$view->setDisplay('page_1');
$view->preExecute();
$view->execute();
foreach ($view->result as $k => $v) {
$entity = $v->_entity;
// Grab image entity.
$image = $entity->get('field_images')->getValue();
// Load the first value for preview image.
$image_entity = File::load($image[0]['target_id']);
// Grab the uri of that first image.
$image_uri = $image_entity->get('uri')->value;
// Using ImageStyle you then load your style.
$style = ImageStyle::load('my_image_style');
// Use buildUrl to create the path to your styled image.
$image_url = $style->buildUrl($image_uri);
// Then I return the url as an image variable to grab in page template.
$projects[$k]['image'] = $image_url;
}
return $projects;
}
}