使用以下用于上传图像的PHP代码上传时缩小图像大小 [英] reduce image size while uploading using the following PHP code used to upload image

查看:170
本文介绍了使用以下用于上传图像的PHP代码上传时缩小图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用以下代码将图像上传到服务器
以下使用以下给定代码完成以下操作

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


  • 上传文件重命名
    我需要的是我需要使用以下代码缩小图像大小

这是代码

 $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

推荐答案

当然,它运作正常。我在PHP中使用这个类:

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.

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

这篇关于使用以下用于上传图像的PHP代码上传时缩小图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆