简体   繁体   English

在php中上传时出现黑色图像

[英]Black images when uploading in php

Upload, at the front end, seems to work and although all the files are created successfully, they are all completely black. 前端的上传似乎可以正常工作,尽管所有文件都已成功创建,但它们都是黑色的。 I'm sure it's something simple I am doing wrong but I've been staring at it for a while and I'm just not getting it. 我敢肯定这很简单,我做错了,但我一直盯着它看了一段时间,但我没有明白。

I'm also untrained in php and I am trying to teach myself along the way. 我也没有接受过php方面的培训,并且正尝试自学。

I have been resizing the images proportionally and some of the widths and heights do have real numbers, does this make a difference? 我一直按比例调整图像的大小,某些宽度和高度的确有实数,这有什么区别吗? Should I round them to the nearest pixel? 我应该将它们四舍五入到最近的像素吗?

Below is the section of code where the error is occurring. 下面是发生错误的代码部分。 I think I know the line that is causing the issues, so I have marked it with "//error". 我想我知道引起问题的那一行,所以我用“ // error”标记了它。

//Resize proportionally
for($i=0;$i<$image_count;$i++){
    $size = getimagesize($_FILES["fileToUpload"]["tmp_name"][$i]);
    $ratio = $size[0]/$size[1]; // width/height
    echo "<BR>Original width = ".$size[0]." Original height = ".$size[1]."<BR>";
    if( $ratio > 1) {
        $width = 500;
        $height = 500/$ratio;
    }
    else {
        $width = 500*$ratio;
        $height = 500;
    }
    echo "<BR>new width = ".$width." new height = ".$height."<BR>";
    // resample
    $image_p[$i] = imagecreatetruecolor($width, $height);
    $image[$i] = imagecreatefromjpeg($_FILES["fileToUpload"]["tmp_name".$i][$i]); //error
    imagecopyresampled($image_p[$i], $image[$i], 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
    //echo "<BR>image".$i." has been resized and resampled";
}

I've also edited my php.ini file to include the following. 我还编辑了php.ini文件以包括以下内容。

1.  ; Maximum size of POST data that PHP will accept.  
2.  post_max_size = 700M  
3.    
4.  ; Maximum number of files. Added by DJ  
5.  max_file_uploads=500  
6.    
7.  ; Maximum allowed size for uploaded files. Added by DJ  
8.  upload_max_filesize = 50M  

Any help would be appreciated. 任何帮助,将不胜感激。

Initially I wasn't sure about the intended end for the script as the code posted was only a portion but if I have now understood correctly then the image processing has the end goal of saving a modified version of the uploaded file? 最初,我不确定脚本的预期目标,因为所发布的代码只是一部分,但是如果我现在已经正确理解,那么图像处理的最终目标就是保存上载文件的修改版本?

<?php
    define('KB',1024);
    define('MB',pow(KB,2));
    define('GB',pow(KB,3));
    define('TB',pow(KB,4));


    function uploaderror( $error ){ 
        switch( $error ) { 
            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 size( $i ) {
        if ( is_numeric( $i ) ) {
            if( $i > 0 && $i < KB ) {
                return "{$i} bytes";
            } elseif( $i >= KB && $i < MB ) {
                return round( ( $i / KB ),2 )."Kb";
            } elseif( $i >= MB && $i < GB ) {
                return round( ( $i / MB ),2 )."Mb";
            } elseif( $i >= GB && $i < TB ) {
                return round( ( $i / GB ),2 )."Gb";
            } elseif( $i >= TB ) {
                return round( ( $i / TB ),2 )."Tb";
            } else {
                #Computer will die
            }
        }
    }

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

        $errors=array();
        $feedback=array();

        /* maximum width or height */
        $maxdim=500;

        /* Obtain reference to files collection */
        $files=(object)$_FILES['fileToUpload'];

        /* location images will be saved to */
        $outputdir='c:/temp/fileuploads/2/';

        /* Process all files */
        if( count( $files->name ) > 1 ){

            /* Iterate through files collection */
            foreach( $files->name as $i => $void ){
                try{

                    $name = $files->name[$i];
                    $size = size( $files->size[$i] );
                    $type = $files->type[$i];
                    $tmp  = $files->tmp_name[$i];
                    $error= $files->error[$i];

                    /* save the file as */
                    $filename = $outputdir . $name;


                    if( !$error == UPLOAD_ERR_OK or !is_uploaded_file( $tmp ) ) throw new Exception( uploaderror( $error ) );
                    else {

                        list( $w, $h, $t, $a ) = getimagesize( $tmp );
                        $ratio = $w / $h;

                        if( $ratio==1 ){
                            $width=$height=$maxdim;
                        } else {
                            $width=ceil( $maxdim * $ratio );
                            $height=$maxdim;
                        }

                        $target=imagecreatetruecolor( $width, $height );
                        $source=imagecreatefromjpeg( $tmp );
                        $result=imagecopyresampled( $target, $source, 0, 0, 0, 0, $width, $height, $w, $h );

                        if( $result ){
                            /* save the modified image to disk */
                            $status=imagejpeg( $target, $filename );
                            $newsize = size( filesize( $filename ) );

                            /* free resources */
                            imagedestroy( $target );
                            imagedestroy( $source );

                            /* delete uploaded temp file */
                            @unlink( $tmp );

                            if( !$status )throw new Exception( 'Unable to save ' . $filename );
                            else $feedback[]="Success: '{$name}' saved as '{$filename}' was {$size} now {$newsize} - resized from dimensions [ W:{$w}, H:{$h} ] to [ W:{$width}, H:{$height} ] ";
                        }
                    }


                }catch( Exception $e ){
                    $errors[]=$e->getMessage();
                    continue;
                }
            }
            if( !empty( $errors ) ) echo '<pre>',print_r($errors,true),'</pre>';
            if( !empty( $feedback ) ) echo '<pre>',print_r($feedback,true),'</pre>';
        }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM