PHP代码中的多个调整大小图像不起作用

时间:2018-02-10 12:46:16

标签: php

我是PHP的初学者。我尝试了很多代码用于图像调整大小仅适用于单个图像上传,但我想进行多个图像调整大小。

以下是我在Google上搜索的代码之一。

多张图片上传代码无效

<?php 

if (isset($_POST['submit'])) { 
    for($i=0;$i<count($_FILES['image']['name']);$i++){
function resize($width, $height){ 

    /* Get original image x y*/ 

    list($w, $h) = getimagesize($_FILES['image']['tmp_name'][$i]); 

    /* calculate new image size with ratio */ 

    $ratio = max($width/$w, $height/$h); 

    $h = ceil($height / $ratio); 

    $x = ($w - $width / $ratio) / 2; 

    $w = ceil($width / $ratio); 

    /* new file name */ 

    $path = 'inder/'.$width.'x'.$height.'_'.$_FILES['image']['name'][$i]; 

    /* read binary data from image file */ 

    $imgString = file_get_contents($_FILES['image']['tmp_name'][$i]); 

    /* create image from string */ 

    $image = imagecreatefromstring($imgString); 

    $tmp = imagecreatetruecolor($width, $height); 

    imagecopyresampled($tmp, $image, 

      0, 0, 

      $x, 0, 

      $width, $height, 

      $w, $h); 

    /* Save image */ 

    switch ($_FILES['image']['type'][$i]) { 

      case 'image/jpeg': 

        imagejpeg($tmp, $path, 100); 

        break; 

      case 'image/png': 

        imagepng($tmp, $path, 0); 

        break; 

      case 'image/gif': 

        imagegif($tmp, $path); 

        break; 

      default: 

        exit; 

        break; 

    } 

    return $path; 

    /* cleanup memory */ 

    imagedestroy($image); 

    imagedestroy($tmp); 

  } 

// settings 

$max_file_size = 50000*50000; // 200kb 

$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); 

// thumbnail sizes 

$sizes = array(250 => 250); 





  if( $_FILES['image']['size'][$i] < $max_file_size ){ 

    // get file extension 

    $ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION)); 

    if (in_array($ext, $valid_exts)) { 

      /* resize image */ 

      foreach ($sizes as $w => $h) { 

        $files[] = resize($w, $h); 

      } 



    } else { 

      $msg = 'Unsupported file'; 

    } 

  } else{ 

    $msg = 'Please upload image smaller than 200KB'; 

  } 

} 
}
?> 

单张图片上传代码正常工作

<?php 

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

function resize($width, $height){ 

    /* Get original image x y*/ 

    list($w, $h) = getimagesize($_FILES['image']['tmp_name']); 

    /* calculate new image size with ratio */ 

    $ratio = max($width/$w, $height/$h); 

    $h = ceil($height / $ratio); 

    $x = ($w - $width / $ratio) / 2; 

    $w = ceil($width / $ratio); 

    /* new file name */ 

    $path = 'inder/'.$width.'x'.$height.'_'.$_FILES['image']['name']; 

    /* read binary data from image file */ 

    $imgString = file_get_contents($_FILES['image']['tmp_name']); 

    /* create image from string */ 

    $image = imagecreatefromstring($imgString); 

    $tmp = imagecreatetruecolor($width, $height); 

    imagecopyresampled($tmp, $image, 

      0, 0, 

      $x, 0, 

      $width, $height, 

      $w, $h); 

    /* Save image */ 

    switch ($_FILES['image']['type']) { 

      case 'image/jpeg': 

        imagejpeg($tmp, $path, 100); 

        break; 

      case 'image/png': 

        imagepng($tmp, $path, 0); 

        break; 

      case 'image/gif': 

        imagegif($tmp, $path); 

        break; 

      default: 

        exit; 

        break; 

    } 

    return $path; 

    /* cleanup memory */ 

    imagedestroy($image); 

    imagedestroy($tmp); 

  } 

// settings 

$max_file_size = 50000*50000; // 200kb 

$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); 

// thumbnail sizes 

$sizes = array(250 => 250); 





  if( $_FILES['image']['size'] < $max_file_size ){ 

    // get file extension 

    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); 

    if (in_array($ext, $valid_exts)) { 

      /* resize image */ 

      foreach ($sizes as $w => $h) { 

        $files[] = resize($w, $h); 

      } 



    } else { 

      $msg = 'Unsupported file'; 

    } 

  } else{ 

    $msg = 'Please upload image smaller than 200KB'; 

  } 


}
?> 

我尝试 for loop 进行图片上传。

更新:错误显示: -

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为这个问题可能是$i<count($_FILES['image']['name'])〜在处理数组时我通常会从计数中扣除1 - 所以那就是$i<count( $_FILES['image']['name'] ) - 1;

我修改了一下并重新编写了resize函数,以便它不会在循环内重复声明 - 这本身就会导致错误。

顺便提一下,如果最大值为200Kb,那么您所拥有的最大文件大小计算似乎不正确 - 因为50,000 x 50,000大约是2.3Gb我认为所以我在204800 - [ 1024 x 200 ]

<?php
    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; 
            case UPLOAD_ERR_FORM_SIZE: return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; 
            case UPLOAD_ERR_PARTIAL: return 'The uploaded file was only partially uploaded'; 
            case UPLOAD_ERR_NO_FILE: return 'No file was uploaded'; 
            case UPLOAD_ERR_NO_TMP_DIR: return 'Missing a temporary folder'; 
            case UPLOAD_ERR_CANT_WRITE: return 'Failed to write file to disk'; 
            case UPLOAD_ERR_EXTENSION: return 'File upload stopped by extension'; 
            default: return 'Unknown upload error';
        }
    }


    function resize( $tmp, $name, $type, $origwidth, $origheight, $newwidth, $newheight ){
        /* calculate new image size with ratio */
        $ratio = max( $newwidth / $origwidth, $newheight / $origheight ); 

        $h = ceil( $newheight / $ratio ); 
        $x = ( $origwidth - $newwidth / $ratio ) / 2; 
        $w = ceil( $newwidth / $ratio ); 

        /* new file name */
        $path = __DIR__ . '/inder/'.$newwidth.'x'.$newheight.'_'.$name; 


        /* read binary data from image file */
        $imgString = file_get_contents( $tmp ); 

        /* create image from string */
        $image = imagecreatefromstring( $imgString );
        $tmp = imagecreatetruecolor( $newwidth, $newheight );
        imagecopyresampled( $tmp, $image, 0, 0,  $x, 0, $newwidth, $newheight, $w, $h ); 

        /* Save image */
        switch( $type ) { 
            case 'image/jpeg': imagejpeg( $tmp, $path, 100 ); break; 
            case 'image/png': imagepng( $tmp, $path, 0 ); break; 
            case 'image/gif': imagegif( $tmp, $path ); break; 
            default:
                imagedestroy($image); 
                imagedestroy($tmp);
            return false;
        }
        /* cleanup memory */
        imagedestroy($image); 
        imagedestroy($tmp);

        return $path; 
    }





    $fieldname='image';

    $max_file_size = 204800; // 200kb
    $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); 
    $sizes = (object)array('width'=>250,'height'=>250); 
    $errors = array();
    $files = array();


    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){

        foreach( $_FILES[ $fieldname ]['name'] as $i => $name ) {
            try{

                if( !empty( $_FILES[ $fieldname ]['tmp_name'][$i] ) ) {

                    $name  = $_FILES[ $fieldname ]['name'][$i];
                    $size  = $_FILES[ $fieldname ]['size'][$i];
                    $type  = $_FILES[ $fieldname ]['type'][$i];
                    $tmp   = $_FILES[ $fieldname ]['tmp_name'][$i];
                    $error = $_FILES[ $fieldname ]['error'][$i];

                    $ext=strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
                    $filesize=filesize( $tmp );

                    list( $w,$h,$t,$a )=getimagesize( $tmp );
                    if( !$w or !$h )throw new Exception( sprintf( 'Not an image: %s',$name ) );


                    if( $error == UPLOAD_ERR_OK ){
                        if( is_uploaded_file( $tmp ) ){

                            if( !in_array( $ext, $valid_exts ) ) throw new Exception( sprintf('Invalid file extension: %s', $ext ) );
                            if( $size > $max_file_size ) throw new Exception( sprintf( 'File is too large: %u', $size ) );


                            /* resize image */
                            $result = resize( $tmp, $name, $type, $w, $h, $sizes->width, $sizes->height );
                            if( !$result )throw new Exception( sprintf( 'error resizing %s',$name ) );
                            $files[] = $result;

                        } else {
                            throw new Exception('Possible file upload attack');
                        }
                    } else {
                        throw new Exception( uploaderror( $error ) );
                    }
                } else {
                    throw new Exception( sprintf('"tmp_name" for %s is empty - unable to upload correctly', $_FILES[ $fieldname ]['name'][$i] ) );
                }
            }catch( Exception $e ){
                $errors[]=$e->getMessage();
                continue;
            }
        }
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Multiple File upload</title>
    </head>
    <body>
        <form name='usrupload' method='post' enctype='multipart/form-data'>
            <input type='hidden' name='MAX_FILE_SIZE' value='<?php echo $max_file_size;?>' />
            <input type='file' name='image[]' multiple />
            <input type='submit' />
        </form>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' ){

                if( !empty( $files ) ){
                    printf('<h2>Files uploaded & resized</h2>');
                    foreach( $files as $file ){
                        printf( '%s<br />',$file );
                    }
                }

                if( !empty( $errors ) ){
                    printf('<h2>Errors</h2>');
                    foreach( $errors as $error ){
                        printf('%s<br />',$error);
                    }
                }
            }
        ?>
    </body>
</html>