上传时缩小图像尺寸

时间:2012-08-28 15:01:38

标签: java php javascript

上传时是否可以缩小图像尺寸?

大小可以从2MB减少到500kb或更低或类似的东西 上传文件?

1 个答案:

答案 0 :(得分: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 );

}