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

在php中上载时出现黑色图像,php,image,upload,Php,Image,Upload,在前端,上传似乎可以工作,尽管所有文件都成功创建,但它们都是完全黑色的。我肯定这很简单,我做错了,但我已经盯着它看了一段时间,我就是不明白 我也没有受过php方面的训练,我正在努力自学 我一直在按比例调整图像的大小,一些宽度和高度确实有实数,这有区别吗?我应该把它们四舍五入到最近的像素吗 下面是发生错误的代码部分。我想我知道引起问题的那一行,所以我用“//错误”标记了它 任何帮助都将不胜感激 最初我不确定脚本的预期目的,因为发布的代码只是其中的一部分,但如果我现在理解正确,那么图像处理的最终目标

在前端,上传似乎可以工作,尽管所有文件都成功创建,但它们都是完全黑色的。我肯定这很简单,我做错了,但我已经盯着它看了一段时间,我就是不明白

我也没有受过php方面的训练,我正在努力自学

我一直在按比例调整图像的大小,一些宽度和高度确实有实数,这有区别吗?我应该把它们四舍五入到最近的像素吗

下面是发生错误的代码部分。我想我知道引起问题的那一行,所以我用“//错误”标记了它


任何帮助都将不胜感激

最初我不确定脚本的预期目的,因为发布的代码只是其中的一部分,但如果我现在理解正确,那么图像处理的最终目标是保存上传文件的修改版本

<?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>';
        }
    }
?>


如果传递的x、y坐标不正确(超出图像),图像通常会变黑。尝试调试您的x、y、高度和宽度计算。感谢您的评论。看起来好像从原始图像生成了正确的高度和宽度。但我会继续找,并仔细阅读你的建议。谢谢。如果您试图实际输出一幅(或多幅)图像,请不要
echo
任何内容,您需要使用
imagejpeg()
,并且需要为content type~设置标题,除非保存到disk@RamRaider在代码中,我进一步使用以下代码(imagejpeg($image_p[$I],$target_file[$I],80)){//output echo“
文件“.basename($_FILES[“fileToUpload”][“name”][$i])”已上载。
“;$uploadOK=1;}否则{echo”
很抱歉,上载文件时出错。
”;$uploadOK=0;}如果您回显任何内容并尝试将图像输出到浏览器,您将在图像中获得错误,它将显示blackWow,谢谢。我将花一些时间查看它并更新您。
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  
<?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>';
        }
    }
?>