下面的代码是从O'Reilly书籍中修改的 - 学习PHP,MySQL和JavaScript,可以找到here
为什么所有图像类型都转换为.jpg?
.jpg是否提供最佳质量/尺寸比率?
public static function upload()
{
$email=$_SESSION['email'];
$path1="i8.jpg";
$path2="z_p/$email.jpg";
$path3="i9.jpg";
$path4="z_p/$email-1.jpg";
if(move_uploaded_file($_FILES['ufile']['tmp_name'], $path2))
{
$typeok=TRUE;
switch($_FILES['ufile']['type'])
{
case "image/gif":
$src = imagecreatefromgif($path2);
break;
case "image/jpeg":
case "image/pjpeg":
$src = imagecreatefromjpeg($path2);
break;
case "image/png":
$src = imagecreatefrompng($path2);
break;
default:
$typeok = FALSE;
break;
}
if($typeok)
{
list($w, $h) = getimagesize($path2);
$tw = $w;
$th = $h;
/*Run 1*/
$max = 50;
if($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$dst = imagecreatetruecolor($tw, $th);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imagejpeg($dst, $path2);
imagedestroy($dst);
/* Rune 2 */
$max = 20;
if($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$dst = imagecreatetruecolor($tw, $th);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imagejpeg($dst, $path4);
imagedestroy($dst);
imagedestroy($src);
}
}
else
{
copy($path1, $path2);
copy($path3, $path4);
}
}
答案 0 :(得分:5)
你可以在jpeg文件(或任何一种图像格式)中隐藏许多令人讨厌的惊喜。通过始终以这种方式重新创建图像,您可以确信服务器发布的图像已经过消毒。
答案 1 :(得分:2)
JPEG并不总是提供最佳的尺寸/质量比,它取决于图像内容,如果它有许多渐变的颜色,或者是风景图片,JPEG可能是最佳选择,但对于像截图PNG这样的东西将提供最佳的尺寸/质量比。