skip to Main Content
function compressImage($source, $destination, $quality) {
    // Get image info 
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime']; 
     
    // Create a new image from file 
    switch($mime){ 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($source); 
           imagejpeg($image, $destination, $quality);
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($source); 
            imagepng($image, $destination, $quality);
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($source); 
            imagegif($image, $destination, $quality);
            break; 
        default: 
            $image = imagecreatefromjpeg($source); 
           imagejpeg($image, $destination, $quality);
    } 
    return $destination; 
}


if(isset($_POST['submit'])){

    $conn = $pdo->open();
    $uploadPath = "draft/"; 
        if(isset($_FILES['photo']['name'][0]) && $_FILES['photo']['size'][0] != 0 && $_FILES['photo']['error'][0] == 0) 
        {
         $filesCount = count($_FILES['photo']['name']);
         for($i = 0; $i < $filesCount; $i++) { 
            $ext = pathinfo($_FILES['photo']['name'][$i], PATHINFO_EXTENSION);
            $extensions= array("jpeg","jpg","png");
                  if(in_array($ext,$extensions)=== false){
           $_SESSION['error']  = 'extension not allowed, please choose a .jpg, .jpeg or .png file.';
      }
else{
            $new_filename = time().$i.'.'.$ext;
            // Compress size and upload image 
          compressImage($_FILES["photo"]["tmp_name"][$i], $uploadPath.$new_filename, 75);   
            $allfiles[] = $new_filename;
         }
         }
         $uploaded_img = implode(',',$allfiles);
        }
        else{
            $uploaded_img = '';
        }

        try{
            $stmt = $conn->prepare("INSERT INTO marketplace (category_id, post_userid, userid, name, description, slug, price, photo, suburb_province, counter) VALUES (:category, :post_userid, :userid, :name, :description, :name, :price, :photo, :suburb_province, :counter)");
            $stmt->execute(['category'=>$category, 'post_userid'=>$post_userid, 'userid'=>$userid, 'name'=>$name, 'description'=>$description, 'slug'=>$slug, 'price'=>$price, 'photo'=>$uploaded_img, 'suburb_province'=>$suburb_province, 'counter'=>0]);
            $_SESSION['success'] = 'Product added successfully';

        }
        catch(PDOException $e){
            $_SESSION['error'] = 'Please choose a .jpg, .jpeg or .png file.';
        }

    $pdo->close();
}

Hi there I have a code below which worked properly without the compressImage function. After I tried to incorporate the compress function into my upload script I now get zero bytes file uploaded although it still correctly uploads an array of files

The only problem I need help with is that the uploaded file is just a name.extension with zero bytes.
What am I doing wrong?

2

Answers


  1. There might be a problem with how you are trying to store the image. From what I have seen from your code is that you are using the original file name instead of the compressed file name, This can result in zero bytes being uploaded since the original file is not actually being uploaded. Try using this approach.

    $compressed_image = compressImage($_FILES["photo"]["tmp_name"][$i], $uploadPath.$new_filename, 75);   
    
    $allfiles[] = $compressed_image;
    
    Login or Signup to reply.
  2. I modified only slightly and put together a full working example of what you are trying to accomplish – the compressImage function works and reduces the quality of suitable images perfectly well. Use the returned value from that function in subsequent operations

    <?php
        if( $_SERVER['REQUEST_METHOD']=='POST' ){
            
            $field='photo';
            $quality=75;
            
            
            
            function compressImage( $source, $destination, $quality=75 ) {
                $imgInfo = getimagesize( $source ); 
                $mime = $imgInfo['mime'];
                
                switch( $mime ){
                    case 'image/png': 
                        $image = imagecreatefrompng( $source ); 
                        $res = imagepng( $image, $destination, $quality );
                    break; 
                    case 'image/gif': 
                        $image = imagecreatefromgif( $source ); 
                        $res = imagegif( $image, $destination );
                    break;
                    
                    case 'image/jpeg': 
                    default: 
                        $image = imagecreatefromjpeg( $source ); 
                        $res = imagejpeg( $image, $destination, $quality );
                    break;
                } 
                return $res ? realpath( $destination ) : false; 
            }
    
    
    
            if( isset( $_FILES[ $field ] ) ){
                
                $allfiles=array();
                $extension = array('jpeg','jpg','png','gif');
                $dir='draft';
                
                
                $targetpath=sprintf('%s/%s',__DIR__, $dir );
                $webpath=sprintf('../%s', $dir );
                
                if( !file_exists( $targetpath ) )mkdir( $targetpath, 0777, true );
                
                
                
                
                /* iterate through the files */
                foreach( $_FILES[ $field ]['name'] as $i => $void ) {
                    $errors = array();
                    if( !empty( $_FILES[ $field ]['tmp_name'][$i] ) ) {
                        $name = $_FILES[ $field ]['name'][$i];
                        $size = $_FILES[ $field ]['size'][$i];
                        $type = $_FILES[ $field ]['type'][$i];
                        $tmp  = $_FILES[ $field ]['tmp_name'][$i];
                        $error= $_FILES[ $field ]['error'][$i];
                        $ext  = pathinfo( $name, PATHINFO_EXTENSION );
                        
                        if( $error == UPLOAD_ERR_OK ){
                            if( !in_array( strtolower( $ext ), $extension ) ){
                                $errors[ $name ]=sprintf('File type is invalid. Type:- %s', $ext );
                            }
                            
                            if( empty( $errors ) ){
                                
                                $targetfile = sprintf('%s/%s', $targetpath, $name );
                                $webfile = sprintf('%s/%s', $webpath, $name );                          
                                
                                $allfiles[ $webfile ]=compressImage( $tmp, $targetfile, $quality );
                            }
                        } else {
                            $errors[ $name ]='There was an error';
                        }
                    }
                }
                
                
                
                
                
                printf( '<pre>%s</pre>',print_r( $allfiles, true ) );
                
                
                
                # process allfiles, add to db
                /*
                $sql='insert into marketplace (...) values (...)';
                $stmt=$db->prepare( $sql );
                $args=array(
                    ...
                    ':photo'    =>  implode( ',', array_keys( $allfiles ) ),
                    ...
                );
                $stmt->execute( $args );
                */
            }
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <title>PHP: Multiple file uploads with compression </title>
            <meta charset='utf-8' />
        </head>
        <body>
            <form method='post' enctype='multipart/form-data'>
                <input type='file' name='photo[]' multiple />
                <input type='submit' />
            </form>
        </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search