Using WordPress ‘image_resize()’ PHP function

The image_resize() WordPress PHP function scales down an image to fit a particular size and saves a new copy of the image.

Usage

image_resize($file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality);

Parameters

  • $file (string) – Required. Image file path.
  • $max_w (int) – Required. Maximum width to resize to.
  • $max_h (int) – Required. Maximum height to resize to.
  • $crop (bool) – Optional. Whether to crop image or resize. Default: false.
  • $suffix (string) – Optional. File suffix. Default: null.
  • $dest_path (string) – Optional. New image file path. Default: null.
  • $jpeg_quality (int) – Optional. Image quality percentage. Default: 90.

More information

See WordPress Developer Resources: image_resize

Examples

Basic image resize

This example resizes an image to a maximum width of 200px and a maximum height of 200px.

$file = 'path/to/image.jpg';
$max_w = 200;
$max_h = 200;

$resized_image = image_resize($file, $max_w, $max_h);

Image resize with cropping

This example resizes and crops an image to exactly 300px width and 300px height.

$file = 'path/to/image.jpg';
$max_w = 300;
$max_h = 300;
$crop = true;

$resized_image = image_resize($file, $max_w, $max_h, $crop);

Image resize with custom suffix

This example resizes an image and adds a custom suffix to the file name.

$file = 'path/to/image.jpg';
$max_w = 400;
$max_h = 400;
$suffix = '-resized';

$resized_image = image_resize($file, $max_w, $max_h, false, $suffix);

Image resize to a specific destination

This example resizes an image and saves it to a specific destination path.

$file = 'path/to/image.jpg';
$max_w = 500;
$max_h = 500;
$dest_path = 'path/to/destination/folder/';

$resized_image = image_resize($file, $max_w, $max_h, false, null, $dest_path);

Image resize with custom quality

This example resizes a JPEG image and sets the quality to 70%.

$file = 'path/to/image.jpg';
$max_w = 600;
$max_h = 600;
$jpeg_quality = 70;

$resized_image = image_resize($file, $max_w, $max_h, false, null, null, $jpeg_quality);