使用 php的imagecopyresampled函数生成缩略图(控制图片大小)
用php生成缩略图经常被使用到,尤其是社区论坛里面生成用户头像,这里我写了一个能够产生缩略图的函数
函数的调用示例:
CreateImage('../'.$save_path, '../'.$BaseDir.$child_dir.'/'.$new_file_small, 128, 128);
CreateImage函数定义:
function CreateImage($SrcImageUrl, $DirImageUrl, $Width, $Height)
{
$img;
$srcw;
$new_width;
$srch;
$new_height;
// 图片类型
$type = substr(strrchr($SrcImageUrl, "."), 1);
// 初始化图像
if($type == "jpg")
$img = imagecreatefromjpeg($SrcImageUrl);
if($type == "gif")
$img = imagecreatefromgif($SrcImageUrl);
if($type == "png")
$img = imagecreatefrompng($SrcImageUrl);
$srcw = imagesx($img);
$srch = imagesy($img);
if ($srcw / $srch > $Width / $Height)
{
if ($srcw > $Width)
{
$new_width = $Width;
$new_height = $srch * ($Width / $srcw);
}
else
{
$new_width = $srcw;
$new_height = $srch;
}
}
else
{
if ($srch > $Height)
{
$new_height = $Height;
$new_width = $srcw * ($Height / $srch);
}
else
{
$new_width = $srcw;
$new_height = $srch;
}
}
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $img, 0, 0, 0, 0, $new_width, $new_height, $srcw, $srch);
imagejpeg($new_image, $DirImageUrl);
imagedestroy($img);
imagedestroy($new_image);
}
不过我在网上看到一个更好的代码: