简体   繁体   English

php-将图像上传到文件夹并调整大小到另一个文件夹

[英]php - upload an image to a folder and resize it to an other folder

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 谢谢

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. 已对除gif以外的所有图像类型进行了测试,但是没有预见到该问题。

<?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>

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

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