UploadMany + resize + Thummnail

UploadMany + resize + Thummnail

jalapejalape Posts: 117Questions: 2Answers: 1

Hello,
I am using the uploadMany method to upload image files. Sometimes the images may come from a camera and I wish they could be reduced in size. That is, to admit images of 7Mb, but that are loaded with a maximum of 400Kb.
The images are stored in an uploads folder and I would like a copy reduced to 50% to be saved at the same time in uploads / thumb.
I have only been able to find something in a somewhat old comment, March 2017 and the pre-1.6 version of the Editor.
https://datatables.net/forums/discussion/41169/howto-to-resize-thumbnail-on-upload-file-how-to-reach-the-more-easy-example-for-dummies
My question is if any resize method has been implemented, I have looked for it in the Upload.php file, but I can't find anything.
Thanks

Replies

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    No, there isn't a resize option in Editor, so that thread you point at would be the way to go,

    Colin

  • jalapejalape Posts: 117Questions: 2Answers: 1

    Thank you. I will follow that path.
    Any other contribution is appreciated ...

  • jalapejalape Posts: 117Questions: 2Answers: 1

    I have managed to insert the necessary code to generate the thumbnail, but I would like the name of the files not to correspond to the id of the image, but to keep the original name.
    I've tried using NAME from Upload.php, but it doesn't work for me.
    This is what I have on the server side:

    <?php
    
    // DataTables PHP library
    include( "../../plugin/php_editor/DataTables.php" );
    
    // Alias Editor classes so they are easy to use
    use
        DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
    
    
    /*
     * Example PHP implementation used for the join.html example
     */
    Editor::inst( $db, 'sml_markers' )
    ->field( 
    
        Field::inst( 'sml_markers.id_map' )
        ->validator( Validate::notEmpty( ValidateOptions::inst()
            ->message( 'El campo mapa es necesario' )   
        ) ) 
        ->options( Options::inst()
            ->table( 'sml_maps' )
            ->value( 'id' )
            ->label( 'name' )
        ),
        Field::inst( 'sml_maps.name' ),
    
        Field::inst( 'sml_markers.lat' ),
        Field::inst( 'sml_markers.lon' ),
        Field::inst( 'sml_markers.name' ),
        Field::inst( 'sml_markers.description' ),
    )
    ->join(
        Mjoin::inst( 'imagen_tb' )
        ->link( 'sml_markers.id', 'marker_imagen.marker_id' )
        ->link( 'imagen_tb.id', 'marker_imagen.imagen_id' )
        ->fields(
            Field::inst( 'id' )
            //->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
            //En el servidor es '/mapas/uploads/__NAME__'
            ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/mapas/uploads/__NAME__' )
                ->db( 'imagen_tb', 'id', array(
                    'filename'    => Upload::DB_FILE_NAME,
                    'filesize'    => Upload::DB_FILE_SIZE,
                    'web_path'    => Upload::DB_WEB_PATH,
                    'system_path' => Upload::DB_SYSTEM_PATH,
                    // Este lo he incorporado para adaptarlo a simple-map
                    // Se ha modificado Upload.php en la línea 109
                    'main' => Upload::DB_MAIN
                ) )
                ->validator( Validate::fileSize( 7000000, 'Los archivos deben tener un tamaño inferior a 7MB ' ) )
                ->validator( Validate::fileExtensions( array( 'png', 'jpg', 'jpeg', 'gif' ), "Sube una imagen " ) )
            )
        )
    )
    
    ->leftJoin( 'sml_maps', 'sml_maps.id', '=', 'sml_markers.id_map' )
    
    
    ->process($_POST)
    ->json();
    
  • jalapejalape Posts: 117Questions: 2Answers: 1
    edited April 2021

    Sorry, previously I had not copied all the code

    <?php
    
    // DataTables PHP library
    include( "../../plugin/php_editor/DataTables.php" );
    
    // Alias Editor classes so they are easy to use
    use
        DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
    
    $nombre = "filename";
    
        // Web and thumbs paths to file
        $webPath = '/mapas/uploads/' .$nombre;
        $webPathThumbs1 = '/mapas/uploads/thumb/' .$nombre;
      
        // System paths
        $sysPath = $_SERVER['DOCUMENT_ROOT'] . $webPath;
        $sysPathThumbs1 = $_SERVER['DOCUMENT_ROOT'] . $webPathThumbs1;
    
        // Create an array to be used in function
        $varArray = [
            "webPath"  => $webPath,
            "sysPath" => $sysPath,
            "webPathTumbs1" =>  $webPathThumbs1,
            "sysPathThumbs1" => $sysPathThumbs1,
        ];
    
    // resize function. Use  GD libraries ( native from PHP 5 )
    function make_thumb($src, $dest, $desired_width) {
        if (!file_exists($dest)) {
            $source_image = imagecreatefromjpeg($src);
            $width = imagesx($source_image);
            $height = imagesy($source_image);
            $desired_height = floor($height * ($desired_width / $width));
            $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
            imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
            imagejpeg($virtual_image, $dest);
        }
    }
     
    /*
     * Example PHP implementation used for the join.html example
     */
    Editor::inst( $db, 'sml_markers' )
    ->field( 
        Field::inst( 'sml_markers.id_map' )
        ->validator( Validate::notEmpty( ValidateOptions::inst()
            ->message( 'El campo mapa es necesario' )   
        ) ) 
        ->options( Options::inst()
            ->table( 'sml_maps' )
            ->value( 'id' )
            ->label( 'name' )
        ),
        Field::inst( 'sml_maps.name' ),
    
        Field::inst( 'sml_markers.lat' ),
        Field::inst( 'sml_markers.lon' ),
        Field::inst( 'sml_markers.name' ),
        Field::inst( 'sml_markers.description' ),
    )
    ->join(
        Mjoin::inst( 'imagen_tb' )
        ->link( 'sml_markers.id', 'marker_imagen.marker_id' )
        ->link( 'imagen_tb.id', 'marker_imagen.imagen_id' )
        ->fields(
    
            Field::inst( 'id' )
            ->setFormatter( 'Format::nullEmpty' )
            ->upload(
                // Custom upload actions. start
                Upload::inst(  function ( $file, $id ) use ( $varArray, $db ) {
                        
                    move_uploaded_file( $file['tmp_name'] , $varArray["sysPath"] . '.jpg' );
                    make_thumb($varArray["sysPath"] . '.jpg', $varArray["sysPathThumbs1"]. '.jpg', 480);
                        
                    $db->update(
                        'imagen_tb', // Database table to update
                        [
                            "web_path" => $varArray["webPath"] . '.jpg',
                            "system_path" => $varArray["sysPath"]  . '.jpg', 
                            "web_path_thumb1" => $varArray["webPathTumbs1"] . '.jpg',
                            "system_path_thumb1" => $varArray["sysPathThumbs1"]  . '.jpg',          
                        ],
                        [ "id" => $id ]
                    );
                    return $id;
                } )
                // Custom upload actions. end      
                ->db( 'imagen_tb', 'id', array(
                    'filename'    => Upload::DB_FILE_NAME,
                    'filesize'    => Upload::DB_FILE_SIZE,
                    'web_path'    => '',
                    'system_path' => '',
                    'web_path_thumb1'    => '',
                    'system_path_thumb1' => '',
                ) )
                ->validator( function ( $file ) {
                    return$file['size'] >= 3000000 ?
                    "Files must be smaller than 3000K o 3,0 Mb" :
                    null;
                } )
                ->dbClean( function ( $data ) {
                    // Remove the files from the file system
                    for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
                        unlink( $data[$i]['system_path'] ); // upload file  folder
                        unlink( $data[$i]['system_path_thumb1'] );  //my thumbnails  file folder #1
                    }
                    // Have Editor remove the rows from the database
                    return true;
                } )
                ->allowedExtensions( array(  'jpg'  ), "Please upload an image file, ONLY .jpg " )
            )
        )
    )
    ->leftJoin( 'sml_maps', 'sml_maps.id', '=', 'sml_markers.id_map' )
    
    ->process($_POST)
    ->json();
    

    I think it has to be something like a variable that retrieves the filename, but I don't know how to do it.

    $nombre = "filename";
    
    $webPath = '/mapas/uploads/' .$nombre;
    $webPathThumbs1 = '/mapas/uploads/thumb/' .$nombre;
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    files not to correspond to the id of the image, but to keep the original name.

    The problem with that is, what if user A uploads "Picture 1.jpg" and then user B uploads "Picture 1.jpg". You've got a naming cash and either need to ask the user to rename it, or overwrite the original. Neither is ideal and I'd strongly recommend you don't use this naming scheme.

    Perhaps you could prepend the file id to the name? You'd make use of the $file, $id parameters passed into your custom function for that - e.g.

    move_uploaded_file( $file['tmp_name'] , $varArray["sysPath"] . '/'. $id .'-'. $file['name'] );
    

    Btw, I don't really understand $webPath = '/mapas/uploads/' .$nombre; in your code. $nombre is just the string filename so the path would always be /mapas/uploads/filename/...?

    Allan

  • jalapejalape Posts: 117Questions: 2Answers: 1

    Hi Allan thanks for the reply,
    With this shape it works perfectly.
    In this case I need to keep the name of the image file being uploaded. One option I have seen is to force the filename field to have unique values in the database. The error it produces in the editor is not very elegant, but I will find a way to prevent duplicates and that I can customize it.
    Thank you very much

This discussion has been closed.