Upload Image from Front End and Resize

The following code is taken from my “Dynamic image resize”-plugin.

The plugin takes an ID as well as a string into account. I didn’t delete those lines, as they might be usable for later visitors – check the link anyway.

Retrieve the image by ID or URl

    $hw_string    = image_hwstring( $width, $height );

    $needs_resize = true;

    $error        = false;
    // ID as src
    if ( ! is_string( $src ) )
    {
        $att_id = $src;
        // returns false on failure
        $src    = wp_get_attachment_url( $src );

        // If nothing was found:
        ! $src AND $error = true;
    }
    // Path as src
    else
    {
        $upload_dir = wp_upload_dir();
        $base_url   = $upload_dir['baseurl'];

        // Let's see if the image belongs to our uploads directory...
        $img_url = substr(
             $src
            ,0
            ,strlen( $base_url )
        );
        // ...And if not: just return the image HTML string
        if ( $img_url !== $base_url )
        {
            return $this->get_markup(
                 $img_url
                ,$hw_string
                ,$classes
            );
        }

        // Look up the file in the database.
        $file   = str_replace(
             trailingslashit( $base_url )
            ,''
            ,$src
        );
        $att_id = $this->get_attachment( $file );

        // If no attachment record was found:
        ! $att_id AND $error = true;
    }

Check for Errors

and abort if no Attachment was found. This would mean the upload didn’t end as expected.

    // Abort if the attachment wasn't found
    if ( $error )
    {
        # @TODO Error handling with proper message
        # @TODO Needs a test case
        # remove $file in favor of $error_msg
        /*
        $data = get_plugin_data( __FILE__ );
        $error_msg = "Plugin: {$data['Name']}: Version {$data['Version']}";
        */

        # @TODO In case, we got an ID, but found no image: if ( ! $src ) $file = $att_id;

        return new WP_Error(
             'no_attachment'
            ,__( 'Attachment not found.', 'dyn_textdomain' )
            ,$file
        );
    }

Check already existing image sizes

In case there already was an image of the size we need. This might be the case if the user tries to upload the same image multiple times (which you’d have to check to avoid duplicates).

    // Look through the attachment meta data for an image that fits our size.
    $meta = wp_get_attachment_metadata( $att_id );
    foreach( $meta['sizes'] as $key => $size )
    {
        if (
            $width === $size['width']
            AND $height === $size['height']
            )
        {
            $src = str_replace(
                 basename( $src )
                ,$size['file']
                ,$src
            );
            $needs_resize = false;
            break;
        }
    }

Process the resize

Now we’re sure we got an attachment and need to resize. We as well update the post and attachment post type meta data.

    // If an image of such size was not found, ...
    if ( $needs_resize )
    {
        $attached_file = get_attached_file( $att_id );
        // ...we can create one.
        $resized       = image_make_intermediate_size(
             $attached_file
            ,$width
            ,$height
            ,true
        );

        if ( ! is_wp_error( $resized ) )
        {
            // Let metadata know about our new size.
            $key = sprintf(
                 'resized-%dx%d'
                ,$width
                ,$height
            );
            $meta['sizes'][ $key ] = $resized;
            $src = str_replace(
                 basename( $src )
                ,$resized['file']
                ,$src
            );

            wp_update_attachment_metadata( $att_id, $meta );

            // Record in backup sizes, so everything's
            // cleaned up when attachment is deleted.
            $backup_sizes = get_post_meta(
                 $att_id
                ,'_wp_attachment_backup_sizes'
                ,true
            );

            ! is_array( $backup_sizes ) AND $backup_sizes = array();

            $backup_sizes[ $key ] = $resized;

            update_post_meta(
                 $att_id
                ,'_wp_attachment_backup_sizes'
                ,$backup_sizes
            );
        }

Now everything should be fine and ready to go on.

If you don’t need everything, just drop what you don’t need, but make sure you don’t leave out the needed error checks. Better safe than sorry.