Crop image in wordpress and delete the original image

Asked

Viewed 85 times

3

After the upload of an image in wordpress I would like to make a check if the registered image is larger than the stated limit size, if it is larger I want to delete the original image in the folder upload and keeps only images cropped with thumbnails (media).

I’m using this function on 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 specified that the maximum image size will be 300x300, when sending a 350x350 image it cuts the image to 300x300 size and excludes the original 350x350 image.

How is it possible to do that?

2 answers

1

The 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 gets

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;
}

1


Apply on file 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 the upload. In this case the limit value is 300.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.