0

上传时是否可以减小图像大小?

上传文件时,大小可以从 2MB 减少到 500kb 或更少吗?

4

1 回答 1

1

当然,它工作正常。我在 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 );是上传后您想要多少图像的大小和质量。

调用 PHP 脚本:

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 );

}

于 2012-08-28T15:05:01.227 回答