Getting Zero Bytes File Using PHP Image Resize

✔ Recommended Answer

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>
 There are a few possible reasons why you might be getting a zero-byte file when trying to resize an image using PHP. Here are some things you can check:
  1. Check if the input file exists: Before you start resizing the image, make sure that the file you are trying to resize actually exists and that you have permissions to read it. You can use the file_exists() function to check if the file exists.

  2. Check if the output file path is correct: Make sure that you are specifying the correct path for the output file. Double-check that the path exists and that you have permissions to write to it. You can use the is_writable() function to check if the directory is writable.

  3. Check if you have the necessary PHP extensions installed: The PHP function imagecreatefromjpeg(), which is used to create an image resource from a JPEG file, requires the GD extension to be installed. Check that the extension is installed and enabled.

  4. Check if the image is corrupted: If the input image file is corrupted, then the resizing operation may fail and produce a zero-byte file. Try opening the image file in an image viewer to check if it can be opened correctly.

  5. Check if the output format is supported: Make sure that the output format you are trying to save the resized image in is supported by the PHP installation on your server. You can use the imagetypes() function to check which image formats are supported.

  6. Check if there are any errors or warnings: PHP may output errors or warnings if something goes wrong during the resizing process. Check the PHP error log or use the error_reporting() function to display any errors or warnings on the page.

By checking these things, you should be able to identify the cause of the zero-byte file and resolve the issue.


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755