Impose a Maximum Limit on Image height and width upload size

Clients have been uploading huuuge images, then complaining that the server is running out of memory.

Ofcourse one could bump the amount of memory, but this just introduces an arms race.

What hooks can I add to impose a maximum image size ( dimensions, not filesize ) on files uploaded, e.g. No you can’t upload that 8 Megapixel shot, resize it first to < 2 Megapixels.

To be clear, I am talking about image size, not file size, aka Image height, and Image width

3 Answers
3

Basically you just retrieve the info via getimagesize(), a basic PHP function, a then handle your errors with notes.

The plugin

A basic plugin as a starting point:

<?php
/** Plugin Name: (#67107) »kaiser« Restrict file upload via image dimensions */

function wpse67107_restrict_upload( $file )
{
    $file_data = getimagesize( $file );
    // Handle cases where we can't get any info:
    if ( ! $file_data )
        return $file;

    list( $width, $height, $type, $hwstring, $mime, $rgb_r_cmyk, $bit ) = $file_data;

    // Add conditions when to abort
    if ( 3200728 < $width * $height )
    {
        // I added 100k as sometimes, there are more rows/columns 
        // than visible pixels, depending on the format
        $file['error'] = 'This image is too large, resize it prior to uploading, ideally below 3.2MP or 2048x1536 px.';
    }

    return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'wpse67107_restrict_upload' );

Leave a Comment