如何将图像文件调整为可选大小

时间:2009-09-23 03:06:39

标签: php image image-scaling gd2

我有图像上传表单,用户附加图像文件,并选择图像大小来调整上传的图像文件的大小(200kb,500kb,1mb,5mb,Original)。然后我的脚本需要根据用户的可选大小调整图像文件大小,但我不知道如何实现此功能,

例如,用户上传一个1mb大小的图像,如果用户选择200KB来调整大小,那么我的脚本应该保存200kb大小。

有没有人知道或有类似任务的经验?

感谢您提前回复。

2 个答案:

答案 0 :(得分:5)

使用GD library,使用imagecopyresampled()

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

编辑:如果要将图像文件的大小调整为指定的大小,那就更难了。所有主要的图像格式都使用压缩和压缩率,因为压缩的性质不同。压缩清澈的蓝天,你将获得比人海更好的压缩比。

您可以做的最好的尝试特定尺寸是尝试特定尺寸并查看文件大小,必要时进行调整。

Resize ratio = desired file size / actual file size
Resize multipler = square root (resize ratio)
New height = resize multiplier * actual height
New width = resize multiplier * actual width

这基本上是预期压缩比的近似值。我希望你有一些容忍度(比如+/- 5%),你可以根据需要调整数字。

没有直接的方法可以调整大小到特定的文件大小。最后,我要补充说,调整大小到特定的文件大小是相当不寻常的。调整到特定的高度和/或宽度(保持纵横比)更为常见和预期(由用户)。

正确指出

更新:,这会导致文件大小错误。当您应用两次(一次到高度,一次到宽度)时,比率需要是文件大小比率的平方根。

答案 1 :(得分:2)

使用PHP提供的GD库:

// $img is the image resource created by opening the original file
// $w and $h is the final width and height respectively.
$width = imagesx($img);$height = imagesy($img);
$ratio = $width/$height;

if($ratio > 1){
// width is greater than height
$nh = $h;
$nw = floor($width * ($nh/$height));
}else{
$nw = $w;
$nh = floor($height * ($nw/$width));
}

//centralize image
$nx = floor(($nw- $w) / 2.0);
$ny = floor(($nh-$h) / 2.0);

$tmp2 = imagecreatetruecolor($nw,$nh);
imagecopyresized($tmp2, $img,0,0,0,0,$nw,$nh,$width,$height);

$tmp = imagecreatetruecolor($w,$h);
imagecopyresized($tmp, $tmp2,0,0,$nx,$ny,$w,$h,$w,$h);

imagedestroy($tmp2);imagedestroy($img);

imagejpeg($tmp, $final_file);

这段代码将采用原始图像,调整大小到指定的尺寸。它将首先尝试比率方面调整图像大小,然后裁剪+集中图像,使其很好地落入指定的尺寸。