2009-09-23 111 views
0

我有图像上传表单,用户附加aimage文件,并选择图像大小来调整上传的图像文件(200kb,500kb,1mb,5mb,原始大小)。然后我的脚本需要根据用户的可选尺寸调整图像文件的大小,但我不知道如何实现这个功能,例如,用户上传一个1mb大小的图像,如果用户选择200KB调整大小,那么我的脚本应该保存200kb的大小。如何将图像文件大小调整为可选大小

有谁知道或有类似任务的经验吗?

感谢你提前回复。

回答

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%),你可以根据需要调整数字。

还有就是要调整到一个特定的文件大小没有直接的方法。最后我会补充说,调整大小到一个特定的文件大小是非常不寻常的。调整到特定的高度和/或宽度(保持宽高比)比用户更常见和预期(用户)。

更新:正确指出,这会导致文件大小错误。该比率需要是文件大小比率的平方根,因为您应用了两次(一次为高度,一次为宽度)。

+0

最终你会用一半的文件你想要的大小,因为小数部分“调整率”被平方。如果你有一个1MB的图像,你想要一个(大约)512KB的文件,你需要调整它的大小,以便newheight = sqrt(2)* height(同样适用于宽度) – dcrosta 2009-09-23 03:39:27

+0

谢谢你的有用评论 – taras 2009-09-23 03:39:50

+0

@dcrosta:很对。固定为sqtiply(比例)。 – cletus 2009-09-23 03:44:44

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

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

+0

我的意思是调整图像文件大小,而不是图像大小本身,例如,用户上传一个1mb大小的图像,如果用户选择200KB调整大小,那么我的脚本应该保存200kb的大小。 – taras 2009-09-23 03:18:34

+0

像其他答案一样,如果没有确定的答案,它会保存多少文件大小。 – mauris 2009-09-23 03:54:05