How to get custom image size for image uploaded in Customizer

I’m using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that.

This is the code in my template file:

<img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">

This is the code in my functions.php file to add the custom size:

add_image_size( 'image-thumbnail', 525, 350, true ); 

Solutions Collecting From Web of "How to get custom image size for image uploaded in Customizer"

Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:

$img = get_theme_mod('image-1');
if (!empty ($img)) {
  $img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
  if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
    }
  else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';

In words. Get the mod. If it exists search $img for the occurence of jpg|jpeg|png|gif at the end of the string and then prepend it with the image size, eg ...image-525x350.jpg. If that file does not exist, use the default. If there is no mod, also use the default.

Working from cjbj’s answer, you may need to add delimiters to have your preg_replace work correctly:

$img = get_theme_mod('image-1');
if (!empty ($img)) {
  $img = preg_replace ('/.(jpg|jpeg|png|gif)$/','-525x350$0');
  if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
  }
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';