≡

How to define the size of uploaded images

How to define the size of uploaded images

kkutikkuti Posts: 20Questions: 6Answers: 0

Please how can I define the size of uploaded images. The upload is done quite easily but we need to define the width and height

Replies

  • allanallan Posts: 66,144Questions: 1Answers: 11,028 Site admin

    Hi,

    The server-side libraries for DataTables don't have a built in validator to check the height / width of an uploaded image. The built in validators are Validate::fileExtensions() and Validate::fileSize().

    To check if an uploaded image's dimensions are within certain bounds, you need to use a custom validator. For example:

    Upload::inst( ... )
        ->validator( function ( $file ) {
            // Define your dimension bounds in pixels
            $minWidth  = 200;
            $maxWidth  = 1920;
            $minHeight = 200;
            $maxHeight = 1080;
    
            // Extract image dimensions (suppress warnings with @ in case of corrupted files)
            $imageInfo = @getimagesize( $file['tmp_name'] );
    
            if ( ! $imageInfo ) {
                return "The uploaded file is not a valid image.";
            }
    
            list( $width, $height ) = $imageInfo;
    
            if ( $width < $minWidth || $width > $maxWidth ) {
                return "Image width must be between {$minWidth}px and {$maxWidth}px (current: {$width}px).";
            }
    
            if ( $height < $minHeight || $height > $maxHeight ) {
                return "Image height must be between {$minHeight}px and {$maxHeight}px (current: {$height}px).";
            }
    
            return null;
        } )
    

    It might be an idea to pull that anonymous function out into a regular function that returns a closure if you are planning on using it for more than one field.

    Allan

Sign In or Register to comment.