我有图片上传表单,用户附加图片文件,并选择图片大小来调整上传图片文件的大小(200kb、500kb、1mb、5mb、原始)。然后我的脚本需要根据用户的可选大小调整图像文件大小,但我不确定如何实现此功能,
例如,用户上传一个 1mb 大小的图像,如果用户选择 200KB 来调整大小,那么我的脚本应该以 200kb 大小保存它。
有谁知道或有类似任务的经验?
感谢您提前回复。
我有图片上传表单,用户附加图片文件,并选择图片大小来调整上传图片文件的大小(200kb、500kb、1mb、5mb、原始)。然后我的脚本需要根据用户的可选大小调整图像文件大小,但我不确定如何实现此功能,
例如,用户上传一个 1mb 大小的图像,如果用户选择 200KB 来调整大小,那么我的脚本应该以 200kb 大小保存它。
有谁知道或有类似任务的经验?
感谢您提前回复。
使用GD 库,使用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%),你可以根据需要调整数字。
没有直接的方法可以将大小调整为特定的文件大小。最后,我要补充一点,将大小调整为特定的文件大小是相当不寻常的。调整到特定的高度和/或宽度(保持纵横比)更为常见和预期(用户)。
更新:正如正确指出的那样,这会导致文件大小错误。该比率需要是文件大小比率的平方根,因为您要应用它两次(一次是高度,一次是宽度)。
使用 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);
这段代码将获取原始图像,调整为指定尺寸。它将首先尝试按比例调整图像大小,然后裁剪 + 居中图像,使其完全符合指定的尺寸。