宝哥软件园需要php等比生成图片缩略图,在网上找了一下,发现大部分代码都不能正常使用,有些只是jpg图片生成缩略图的函数,对于gif和png并不能完美实现,生成png以后会出现打不开的情况,所以做了一下小小的修改,可以完美的实现gif ,jpg,png三种图片的生成缩略图。记录一下函数。function reSizeImg($imgSrc, $dstimg, $resize_width, $resize_height, $isCut = false) {
//图片的类型
$type = substr(strrchr($imgSrc, "."), 1);
//初始化图象
if ($type == "jpg" || $type == "jpeg") {
$im = imagecreatefromjpeg($imgSrc);
}
if ($type == "gif") {
$im = imagecreatefromgif($imgSrc);
}
if ($type == "png") {
$im = imagecreatefrompng($imgSrc);
}
$width = imagesx($im);
$height = imagesy($im);
//生成图象
//改变后的图象的比例
$resize_ratio = ($resize_width) / ($resize_height);
//实际图象的比例
$ratio = ($width) / ($height);
if (($isCut) == 1) {
if ($ratio >= $resize_ratio) {
//高度优先
$newimg = imagecreatetruecolor($resize_width, $resize_height);
imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height);
createImg($type, $newimg, $dstimg);
}
if ($ratio
//宽度优先
$newimg = imagecreatetruecolor($resize_width, $resize_height);
imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $resize_ratio));
createImg($type, $newimg, $dstimg);
}
} else {
if ($ratio >= $resize_ratio) {
$newimg = imagecreatetruecolor($resize_width, ($resize_width) / $ratio);
imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height);
createImg($type, $newimg, $dstimg);
}
if ($ratio
$newimg = imagecreatetruecolor(($resize_height) * $ratio, $resize_height);
imagecopyresampled($newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height);
createImg($type, $newimg, $dstimg);
}
}
ImageDestroy($im);
}
function createImg($type, $newimg, $dstimg)
{
//初始化图象
if ($type == "jpg" || $type == "jpeg") {
imagejpeg($newimg, $dstimg);
}
if ($type == "gif") {
imagegif($newimg, $dstimg);
}
if ($type == "png") {
imagepng($newimg, $dstimg);
}
}
调用方法:reSizeImg($原图地址,$新图地址,300,200);
这样就可以实现等比例成生成缩略图了。