php 用GD库生成高质量的缩略图片示例代码

php教程评论534 views阅读模式

在网站上GD库通常用来生成缩略图,或者用来对图片加水印,或者用来生成汉字验证码,或者对网站数据生成报表等。在PHP处理图像,可使用GD库,而GD库开始时是支持GIF的,但由于GIF使用了有版权争议的LZW算法,会引起法律问题,于是从 GD 库 1.6 版起所有的 GIF 支持都移除了,但是又在 GD 库 2.0.28 版起又加了回来。如果使用二者之间版本的 GD 库时 GIF 相关函数不可用。本文章主要介绍php 用GD库生成高质量的缩略图片的示例代码

以下是PHP源代码(ResizeImage.php)。

<?php 
$FILENAME="image.thumb"; 
// 生成图片的宽度 
$RESIZEWIDTH=400; 
// 生成图片的高度 
$RESIZEHEIGHT=400; 

function ResizeImage($im,$maxwidth,$maxheight,$name){ 
$width = imagesx($im); 
$height = imagesy($im); 
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ 
if($maxwidth && $width > $maxwidth){ 
$widthratio = $maxwidth/$width; 
$RESIZEWIDTH=true; 
} 
if($maxheight && $height > $maxheight){ 
$heightratio = $maxheight/$height; 
$RESIZEHEIGHT=true; 
} 
if($RESIZEWIDTH && $RESIZEHEIGHT){ 
if($widthratio < $heightratio){ 
$ratio = $widthratio; 
}else{ 
$ratio = $heightratio; 
} 
}elseif($RESIZEWIDTH){ 
$ratio = $widthratio; 
}elseif($RESIZEHEIGHT){ 
$ratio = $heightratio; 
} 
$newwidth = $width * $ratio; 
$newheight = $height * $ratio; 
if(function_exists("imagecopyresampled")){ 
$newim = imagecreatetruecolor($newwidth, $newheight); 
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
}else{ 
$newim = imagecreate($newwidth, $newheight); 
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
} 
ImageJpeg ($newim,$name . ".jpg"); 
ImageDestroy ($newim); 
}else{ 
ImageJpeg ($im,$name . ".jpg"); 
} 
} 

if($_FILES['image']['size']){ 
if($_FILES['image']['type'] == "image/pjpeg"){ 
$im = imagecreatefromjpeg($_FILES['image']['tmp_name']); 
}elseif($_FILES['image']['type'] == "image/x-png"){ 
$im = imagecreatefrompng($_FILES['image']['tmp_name']); 
}elseif($_FILES['image']['type'] == "image/gif"){ 
$im = imagecreatefromgif($_FILES['image']['tmp_name']); 
} 
if($im){ 
if(file_exists("$FILENAME.jpg")){ 
unlink("$FILENAME.jpg"); 
} 
ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME); 
ImageDestroy ($im); 
} 
} 
?>

以下是测试代码(demo.php) 代码如下:

<?php 
include('ResizeImage.php'); 
if(!empty($_POST)){ 
echo($FILENAME.".jpg?cache=".rand(0,999999)); 
} 
?> 
<form name="test" action="?submit=true" enctype="multipart/form-data" method="post" > 
<input type="file" name="image" size="50" value="浏览"><p> 
<input type="submit" value="上传图片"> 
</form>

以上就是php 用GD库生成高质量的缩略图片示例代码的详细内容,更多请关注php教程网其它相关文章!

企鹅博客
  • 本文由 发表于 2020年1月16日 15:51:17
  • 转载请务必保留本文链接:https://www.qieseo.com/241992.html

发表评论