PHP 实现缩略图

时间:2022-10-17 23:06:30

PHP 实现缩略图

<?php
header("Content-type: image/png");

function resize_image($filename, $tmpname, $xmax, $ymax)
{

$ext = explode(".", $filename);
$ext = $ext[count($ext)-1];

//判断文件类型,获取不同的图像
if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);

//获取原图的高度和宽度
$x = imagesx($im);
$y = imagesy($im);

if($x <= $xmax && $y <= $ymax)
return $im;

//按比例缩放
if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
//创建新图像
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
//输出资源
imagejpeg(resize_image('nriven.jpg','riven.jpg',300,300));
?>