<?php
$filename = 'images/1.jpg';
if ($fileInfo = getimagesize($filename)) {
list($src_w, $src_h) = $fileInfo;
} else {
exit('文件不是真实图片');
}
$dst_w = 300;
$dst_h = 600;
$ratio_orig = $src_w / $src_h;
if ($dst_w / $dst_h > $ratio_orig) {
$dst_w = $dst_h * $ratio_orig;
} else {
$dst_h = $dst_w / $ratio_orig;
}
$src_image = imagecreatefromjpeg($filename);
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
imagepng($dst_image, 'images/test_thumb.jpg');
imagedestroy($src_image);
imagedestroy($dst_image);
?>
优化
适应不同格式的图片
<?php
$filename = 'images/miao.gif';
if ($fileInfo = getimagesize($filename)) {
list($src_w, $src_h) = $fileInfo;
$mime = $fileInfo['mime'];//image/gif image/jpeg
} else {
exit("文件不是真实图片");
}
//imagecreatefromjpeg imagecreatefromgif imagecreatefrompng
$createFun = str_replace('/', 'createfrom', $mime);
//imagejpeg imagepng imagegif
$outFun = str_replace('/', null, $mime);
$dst_w = 300;
$dst_h = 600;
$ratio_orig = $src_w / $src_h;
if ($dst_w / $dst_h > $ratio_orig) {
$dst_w = $dst_h * $ratio_orig;
} else {
$dst_h = $dst_w / $ratio_orig;
}
$src_image = $createFun($filename);
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
$outFun($dst_image, 'images/test1_thumb.jpg');
imagedestroy($src_image);
imagedestroy($dst_image);
?>