Prevent large image uploads

I want to prevent users in my blog from uploading large size images. And I mean large in px size not MB. Max Upload is set to 8MB which should be ok but I wan’t to prevent uploading for images larger than 3000x3000px.

Is there any hook I am missing that I could write a function for to tell users their image is too large?

1 Answer
1

You have a few different solutions available here:

Automatically scaling down

If you just do not want to store huge amounts of image data on your webspace, I’d recommend the Plugin Imsanity. This automatically scales down the uploaded images, even if they are too big.

Forbid large uploads

In this case the user has more work to do, as they will have to scale down the images on their own. You could filter the wp_handle_upload_prefilter:

add_filter('wp_handle_upload_prefilter', 'f711_image_size_prevent');
function f711_image_size_prevent($file) {
    $size = $file['size'];
    $size = $size / 1024; // Calculate down to KB
    $type = $file['type'];
    $is_image = strpos($type, 'image');
    $limit = 5000; // Your Filesize in KB

    if ( ( $size > $limit ) && ($is_image !== false) ) {
        $file['error'] = 'Image files must be smaller than '.$limit.'KB';
    }

    return $file;

}

Change the PHP values

This one is fairly straight forward, you just have to set max_upload_size in your .htaccess or php.ini.

Leave a Comment