There are several scripts to resize image on the fly such as Aqua Resizer, vt_resizer, script by Konstantin Kovshenin, Dynamic Image Resizer, and so on. They are great and work perfectly. But it seems a lot to me. All I want is a script that resize an image which is passed by attachment ID (not URL), that’s all. And here is what I get:

Update 1: The script is updated to work if the image is smaller than the crop size. Thanks @Isaac.
Update 2: Check if resized file exists and remove it when the attachment is removed.

function rw_image_resize( $attachment_id, $width, $height, $crop = true )
{
    $path = get_attached_file( $attachment_id );
    if ( ! file_exists( $path ) )
    {
        return false;
    }

    $upload    = wp_upload_dir();
    $path_info = pathinfo( $path );
    $base_url  = $upload['baseurl'] . str_replace( $upload['basedir'], '', $path_info['dirname'] );

    $meta = wp_get_attachment_metadata( $attachment_id );
    foreach ( $meta['sizes'] as $key => $size )
    {
        if ( $size['width'] == $width && $size['height'] == $height )
        {
            return "{$base_url}/{$size['file']}";
        }
    }

    // Generate new size
    $resized = image_make_intermediate_size( $path, $width, $height, $crop );
    if ( $resized && ! is_wp_error( $resized ) )
    {
        // Let metadata know about our new size.
        $key                 = sprintf( 'resized-%dx%d', $width, $height );
        $meta['sizes'][$key] = $resized;
        wp_update_attachment_metadata( $attachment_id, $meta );
        return "{$base_url}/{$resized['file']}";
    }

    // Return original if fails
    return "{$base_url}/{$path_info['basename']}";
}

The script is created with references from the scripts above, mostly from Aqua Resizer and script by Konstantin Kovshenin. I just want a simpler version which shows the logic more clearly. Hope that’s useful for you, too.

11 Comments

    1. That’s nice! I’ve looked at all scripts (yours is similar) and found that the complexity comes from the idea of processing URL instead of attachment ID (like mine). We rarely use URL nowadays while we always have attachment ID 🙂

  1. Is there any wordpress plugin that can take the input of dimensions and process all the images. like we can create profiles of multiple dimensions. not just thumbnails. that would make it easy to use in content. Having just three size profile doesn’t really work sometimes.

  2. It is simple , just copy/paste the code below into your WordPress theme’s functions.php file of your currently activated WordPress theme.

  3. That’s a great script! I have tried deactivating image resize plugin and putting this script into functions.php. It works like a charm.

  4. I’m getting an error 🙁
    Undefined index: extension

    I can see that my vars are being collected by the function, but I guess that something is missing….

  5. Can you please tell me how can I use multiple resolutions for an wallpaper site using this script ? I have an wallpaper site and a script that convert images but it is not using wordpress functions, and cosnume a lot of CPU and gives me a lot of errors.

    Also the images cropped are saved on the disk ?

    1. To make it work for multiple resolutions, you just need to call this function multiple times with different width and height. This function uses WordPress function, so it will crop as expected.

  6. Thanks for the script, it works well except if the image is smaller than the crop size; the new filename doesn’t actually match what was asked for.

    An image at 1750 x 1250 with a requested crop of 1900 x 1200 creates image at 1750 x 1200, with a file name of “my-image-1750×1200.jpg” and not “my-image-1900×1200.jpg”.

    Here’s a revised version of the script that fixes this problem by returning the actual filename that was created:
    https://gist.github.com/isaacwebfix/e311198b799ec25b7536

Leave a Reply