avatar Deluxe Blog Tips About Projects

How to resize image on the fly in WordPress

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.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Comments