function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {}

Scale down an image to fit a particular size and save a new copy of the image.
The PNG transparency will be preserved using the function, as well as the image type. If the file going in is PNG, then the resized image is going to be PNG. The only supported image types are PNG, GIF, and JPEG.


  • string $file: Image file path.
  • int $max_w: Maximum width to resize to.
  • int $max_h: Maximum height to resize to.
  • bool $crop: Optional. Whether to crop image or resize.
  • string $suffix: Optional. File suffix.
  • string $dest_path: Optional. New image file path.
  • int $jpeg_quality: Optional, default is 90. Image quality percentage.

Return values

returns:WP_Error on failure. String with new destination path.

Source code

function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {

	$image = wp_load_image( $file );

	if ( !is_resource( $image ) )

		return new WP_Error( 'error_loading_image', $image, $file );

	$size = @getimagesize( $file );

	if ( !$size )

		return new WP_Error('invalid_image', __('Could not read image size'), $file);

	list($orig_w, $orig_h, $orig_type) = $size;

	$dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);

	if ( !$dims )

		return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );

	list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;

	$newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );

	imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

	// convert from full colors to index colors, like original PNG.

	if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )

		imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );

	// we don't need the original in memory anymore

	imagedestroy( $image );

	// $suffix will be appended to the destination filename, just before the extension

	if ( !$suffix )

		$suffix = "{$dst_w}x{$dst_h}";


No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: