按图像大小压缩图像

时间:2018-02-10 08:54:54

标签: javascript php jquery ajax

是否可以使用PHP按大小压缩图像?我的意思是我让用户以KB为单位输入图像的大小,然后获得该大小的图像。

1 个答案:

答案 0 :(得分:1)

您可以通过使用新尺寸重新创建图像来压缩图像。

$image_name = $_FILES['image']['name'];
$image_name_tmp = $_FILES['image']['tmp_name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);

if($ext=='jpg' || $ext=='jpeg' || $ext=='JPG' || $ext=='JPEG')
{
    $src = imagecreatefromjpeg($image_name_tmp);
}
else if($ext=="png" || $ext=="PNG")
{
$src = imagecreatefrompng($image_name_tmp);
}
else 
{
$src = imagecreatefromgif($image_name_tmp);
}


list($width, $height) = getimagesize($image_name_tmp);

$n_width = 320;
$n_height = ($height / $width) * $n_width;

$temp_image = imagecreatetruecolor($n_width, $n_height);
imagecopyresampled($temp_image, $src, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
imagejpeg($temp_image, $target, 100);