Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

reduce image size while uploading using the following PHP code used to upload image

Am trying to upload image to server using the following code Following are done with the given code below

  • Upload file renaming
    What i need is i need to reduce image size with the following code

Here is the code

 $file_name = $HTTP_POST_FILES['ufile']['name'];
 $random_digit = md5(rand() * time());
 $new_file_name = $random_digit . $file_name;
 $path = "upload/" . $new_file_name;
 if ($ufile != none) {
    if (copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)) {
        echo "Successful<BR/>";
        echo "File Name :" . $new_file_name . "<BR/>";
        echo "File Size :" . $HTTP_POST_FILES['ufile']['size'] . "<BR/>";
        echo "File Type :" . $HTTP_POST_FILES['ufile']['type'] . "<BR/>";
    } else {
        echo "Error";
    }
 }

how to reduce image size with the given code

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, it works fine. I use this class in PHP:

<?php

function thumbnail( $img, $source, $dest, $maxw, $maxh ) {      
    $jpg = $source.$img;

    if( $jpg ) {
        list( $width, $height  ) = getimagesize( $jpg ); //$type will return the type of the image
        $source = imagecreatefromjpeg( $jpg );


        if( $maxw >= $width && $maxh >= $height ) {
            $ratio = 1;
        }elseif( $width > $height ) {
            $ratio = $maxw / $width;
        }else {
            $ratio = $maxh / $height;
        }

        $thumb_width = round( $width * $ratio ); //get the smaller value from cal # floor()
        $thumb_height = round( $height * $ratio );

        $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
        imagecopyresampled( $thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height );

        $path = $dest.$img."_thumb.jpg";
        imagejpeg( $thumb, $path, 75 );
    }
    imagedestroy( $thumb );
    imagedestroy( $source );
}

?>

imagejpeg( $thumb, $path, 75 );

is where how much you want the size and quality of the image after uploading.

Calling in PHP script:

if( isset( $_FILES['img-content'] ) ) {
$img = str_replace( " ","_",$_FILES['img-content']['name'] );
move_uploaded_file( $_FILES['img-content']['tmp_name'], "../../images/content/".$img );
$source = "../../images/content/";
$dest = "../../images/thumb/";
thumbnail( $img, $source, $dest, 480, 400 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...