Wordpress image cropping and deletion of the original image

3
After the upload of an image in wordpress I would like to make a check if the registered image is larger than the declared size limit, if it is larger I want to delete the original image in upload folder and keep only images trimmed with thumbnails .

I'm using this function in functions.php

add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
    $upload_dir = wp_upload_dir();
    $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
    $deleted = unlink( $full_image_path );

    return $metadata;
}

Example:

I have specified that the maximum size of the images will be 300x300, when sending a 350x350 image it will crop the image to the size of 300x300 and delete the original image of 350x350.

How can this be done?

    
asked by anonymous 15.10.2015 / 14:17

2 answers

1

Apply to functions.php

add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
    $upload_dir = wp_upload_dir();
    $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
    if($metadata['width'] >= '300'){
     $deleted = unlink( $full_image_path );
    }    
    return $metadata;
}

With this function you can reach the width of the image before upload . In this case the limit value is 300.

    
15.10.2015 / 15:26
1

PHP has a method called getimagesize() which, as the name says, returns the image size. For example

$filepath = 'https://upload.wikimedia.org/wikipedia/en/c/c2/Peter_Griffin.png';

$size = getimagesize($filepath);

var_dump($size);

returns

array(6) { [0]=> int(247) [1]=> int(359) [2]=> int(3) [3]=> string(24) "width="247" height="359"" ["bits"]=> int(8) ["mime"]=> string(9) "image/png" }

The first two positions of this array represent, respectively, the length and height of your image. With this, just make a comparison before deleting the image. Your code stays

add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata ){
    $upload_dir = wp_upload_dir();
    $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
    $size = getimagesize($full_image_path);

    if(($full_image_path[0] < 300) and ($full_image_path[1] < 300)){
        $deleted = unlink( $full_image_path );
    }

    return $metadata;
}
    
15.10.2015 / 15:13