dou426098 2019-03-02 06:51
浏览 68
已采纳

php - 将图像上传到文件夹并将其大小调整为其他文件夹

i have tow codes, one upload an image and another resize image, but i can't put this codes together to upload to a folder and resize it to another folder.

this is normal upload code :

<?php
if (isset($_POST["submitp"])) {
    $ppic="456.png";    
    $file_tmp = $_FILES['ppic']['name'];
    $ppicpath="_prf/u/".$ppic;
    move_uploaded_file($_FILES["ppic"]["tmp_name"],$ppicpath);

}
?><form action="" method="post" enctype="multipart/form-data" style="position: relative;top: -20px;z-index: 1">
 <input type="file" name="ppic" class="button2"  >
 <input type="submit" name="submitp" value="submit">
 </form>

and this is resize code and move to another folder:

<?php
if (isset($_POST["submitp"])) {
        $ppic = "123.png";
        $uploadO = 1;
        $path_thumbs = "_prf/u2/";
        //the new width of the resized image, in pixels.
        $img_thumb_width = 150; // 

        $extlimit = "yes";

        $limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");

        //the image -> variables
        $file_type = $_FILES['ppic']['type'];
        $file_name = $_FILES['ppic']['name'];
        $file_size = $_FILES['ppic']['size'];
        $file_tmp = $_FILES['ppic']['tmp_name'];

       $ext = strrchr($file_name,'.');
       $ext = strtolower($ext);
       //uh-oh! the file extension is not allowed!
       if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
          echo "Wrong file extension. <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }

       $getExt = explode ('.', $file_name);
       $file_ext = $getExt[count($getExt)-1];

       $rand_name= "123.png";

        $ThumbWidth = $img_thumb_width;

       // CREATE THE THUMBNAIL //

    if($file_size){
          if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
               $new_img = imagecreatefromjpeg($file_tmp);
           }elseif($file_type == "image/x-png" || $file_type == "image/png"){
               $new_img = imagecreatefrompng($file_tmp);
           }elseif($file_type == "image/gif"){
               $new_img = imagecreatefromgif($file_tmp);
           }

        list($width, $height) = getimagesize($file_tmp);

           $imgratio=$width/$height;
           if ($imgratio>1){
              $newwidth = $ThumbWidth;
              $newheight = $ThumbWidth/$imgratio;
           }else{
                 $newheight = $ThumbWidth;
                 $newwidth = $ThumbWidth*$imgratio;
           }

           $resized_img = imagecreatetruecolor($newwidth,$newheight);

           imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

            ImageJpeg ($resized_img,"$path_thumbs/$rand_name");
           ImageDestroy ($resized_img);
           ImageDestroy ($new_img);

       }

      if ($uploadO == 0) {
          echo "Sorry, your file was not uploaded."; 
            }elseif($uploadO == 1){   

    move_uploaded_file ("$path_thumbs/$rand_name", $file_tmp);
}
}
?><form action="" method="post" enctype="multipart/form-data" style="position: relative;top: -20px;z-index: 1">
 <input type="file" name="ppic" class="button2"  >
 <input type="submit" name="submitp" value="submit">
 </form>

i can't put this codes together to upload to a folder and resize it to another folder. thanks

  • 写回答

1条回答 默认 最新

  • drlu11748 2019-03-02 13:50
    关注

    The following demo ought to help solve the problem - some minor editing to the directories used will be required. There are comments throughout which should help - it is, after-all, not too different to the pieces of code you had. This was tested on all image types except gif but don't foresee issue with that.

    <?php
        /*  Single file upload with resized thumbnail generation */
    
    
        # The name of the HTML file field
        $field='ppic';
        # The base directory for uploads
        $rootdir=realpath( __DIR__ . '/upload' );
        # The directory into which images will be saved
        $imagedir=sprintf( '%s/images', $rootdir );
        # The directory into which a new thumbnail will be generated
        $thumbsdir=sprintf( '%s/images/thumbs', $rootdir );
        # For PNG files, the default compression level ( normally 6 )
        $compression = 3;
        # Set to boolean again later to indicate success/failure
        $response = false;
        # max image width
        $imgwidth=150;
        # max file size
        $maxsize = pow( 1024, 2 ) * 2;  # 2Mb   
        # allowed file extensions
        $extensions=array('jpg','jpeg','png','gif','bmp');
        # allowed mimetypes
        $mimetypes=array('image/jpeg','image/png','image/gif','image/x-ms-bmp');            
    
    
    
    
        if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES[ $field ] ) ){
            try{
    
                # simple supporting functions
                function createdir( $path=null, $perm=0644 ) {
                    if( !file_exists( $path ) ) {
                        mkdir( $path, $perm, true );
                        clearstatcache();
                    }
                }
                function getratio( $w=false, $h=false ){
                    return $w & $h ? $w / $h : false;
                }
                function getaspect( $w, $h ){
                    if( $w==$h )return 's';
                    elseif( $w > $h )return 'l';
                    elseif( $h > $w )return 'p';
                    else return 'e';
                }
                function getsize( $size ){
                     $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
                     $power = $size > 0 ? floor( log( $size, 1024 ) ) : 0;
                     return number_format( $size / pow( 1024, $power ), 2, '.', ',' ) . ' ' . $units[ $power ];
                }
    
    
                # ensure target directory structure exists
                createdir( $imagedir );
                createdir( $thumbsdir );
    
    
                $obj=(object)$_FILES[ $field ];
                $name=$obj->name;
                $tmp=$obj->tmp_name;
                $size=$obj->size;
                $type=$obj->type;
                $error=$obj->error;
    
                $ext=strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
                list( $width, $height, $type, $attr )=getimagesize( $tmp );
                $mime=image_type_to_mime_type( $type );
    
                # generate paths for images
                $targetfile = $imagedir . DIRECTORY_SEPARATOR . basename( $name );
                $thumbnail = $thumbsdir . DIRECTORY_SEPARATOR . basename( $name );
    
    
                # some basic tests
                if( !$error == UPLOAD_ERR_OK ) throw new Exception( sprintf('Upload failed with error code %d', $error ) );
                if( !in_array( $ext, $extensions ) ) throw new Exception( sprintf( 'bad file extension (%s)',$ext ) );
                if( !in_array( $mime, $mimetypes ) ) throw new Exception( sprintf( 'bad mime type (%s)', $mime) );
                if( $width < $imgwidth ) throw new Exception( sprintf('image is too small (%s)', $attr ) );
                if( $size > $maxsize ) throw new Exception( sprintf('image is too large ( %s )', getsize( $size ) ) );
    
    
                # save the uploaded image
                if( !is_uploaded_file( $tmp ) ) throw new Exception('file upload attack');
                $status = move_uploaded_file( $tmp, $targetfile );
    
    
                # if the file was saved OK, generate resized thumbnail
                if( $status & imagetypes() ){
    
                    $ratio = getratio( $width, $height );
                    $aspect= getaspect( $width, $height );
    
                    switch( $aspect ){
                        case 's':
                            $thumbwidth = $thumbheight = $imgwidth;
                        break;
                        case 'l':
                            $thumbwidth = $imgwidth;
                            $thumbheight = $thumbwidth / $ratio;
                        break;
                        case 'p':
                            $thumbheight = $imgwidth;
                            $thumbwidth = $thumbheight * $ratio;
                        break;
                        case 'e':throw new Exception('bad foo');
                    }
    
                    # generate new image
                    $thumb = imagecreatetruecolor( $thumbwidth, $thumbheight );
    
                    # use appropriate methods for the type of file uploaded
                    switch( $type ){
                        case IMG_JPG:
                            $source = @imagecreatefromjpeg( $targetfile );
                            if( $source ){
                                @imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
                                @imagejpeg( $thumb,$thumbnail );
                            }                   
                        break;
    
                        case IMG_PNG:
                        case 3:
                            $source = @imagecreatefrompng( $targetfile );
                            if( $source ){
                                @imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
                                @imagepng( $thumb, $thumbnail, $compression );
                            }
                        break;
    
                        case IMG_GIF:
                            $source = @imagecreatefromgif( $targetfile );
                            if( $source ){
                                @imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
                                @imagegif( $thumb, $thumbnail );
                            }
                        break;
    
                        case IMG_WBMP && PHP_VERSION_ID > 70200: # available for PHP v7.2+
                            $source = @imagecreatefrombmp( $targetfile );
                            if( $source ){
                                @imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
                                @imagebmp( $thumb, $thumbnail, true );
                            }
                        break;
                    }
    
    
                    # set the success/failure indicator
                    $response = file_exists( $thumbnail ) && file_exists( $targetfile ) ? true : false;
    
                    @imagedestroy( $thumb );
                    @imagedestroy( $source );               
                    @unlink( $tmp );
    
                    clearstatcache();
                    http_response_code( 200 );
    
                } else {
                    throw new Exception( 'Failed to save the upoaded image' );
                }
            }catch( Exception $e ){
                /* something's gone wrong again */
                $html='
                <html>
                    <head>
                        <meta charset="utf-8" />
                        <title>error</title>
                        <style>
                            body{display:flex;flex-direction:column;width:100%%;height:100vh;color:red;font-family:cursive;padding:0;margin:0}
                            h1,a{width:80%%;margin:auto;text-align:center;}
                        </style>
                    </head>
                    <body>
                        <h1>%s</h1>
                        <a href="javascript:location.href=location.href" target="_top">Reload</a>
                    </body>
                </html>';
                $error=sprintf( 'Error: %s, line: %d', $e->getMessage(), $e->getLine() );
                http_response_code( 400 );
                exit( sprintf( $html, $error ) );
            }
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title>combined image upload & resize</title>
            <style>
                body{display:flex;margin:0;padding:0;height:100vh;font-family:calibri,verdana,arial;}
                html,html *{box-sizing:border-box;}
                form{display:flex;flex-direction:column;margin:auto;width:80%;height:80vh;align-items:center;padding:1rem;}
                form > fieldset{display:flex:flex:1;width:90%;min-width:90%;margin:1rem auto;flex-direction:row;border:1px dashed rgba(100,100,100,0.25);padding:2rem;align-items:center;justify-content:center;}
                input{padding:1rem;}
                [type='file']{border:1px solid rgba(100,100,100,0.25);padding:0.9rem}
            </style>
        </head>
        <body>
            <form method='post' enctype='multipart/form-data'>
                <?php
                    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $response ) ){
                        /*
                            let user know the uploaded succeeded
                            ... or not
    
                            for this demo the upload folder is within the current
                            working directory thus image paths are relative to this
                            and not document root.
                        */
                        printf(
                            '<fieldset>
                                <h3>%s - File uploaded</h1>
                                <a href="%s" target="_blank">
                                    <img src="%s" width=%d height=%d title="%s" alt="%s" />
                                </a>
                            </fieldset>',
                            $name,
                            ltrim( str_replace( array( __DIR__, '\\' ), array('','/'), $targetfile ),'/'),
                            ltrim( str_replace( array( __DIR__, '\\' ), array('','/'), $thumbnail ),'/'),
                            $thumbwidth,
                            $thumbheight,
                            $name,
                            $name
                        );
                    }
                ?>
                <fieldset>
                    <input type='file' name='ppic' />
                    <input type='submit' />
                </fieldset>
            </form>
        </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改