PHP用GD库生成高质量的缩略图片

yipeiwu_com5年前PHP代码库
以下是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字符串过滤,转换函数代码

nl2br();// \n to addslashes(); stripslashes();//对数据库操作时,转义特殊字符 chop();//除去字符串右边空格 trim();//除去...

Apache 配置详解(最好的APACHE配置教程)

Apache的配置 Apache的配置由httpd.conf文件配置,因此下面的配置指令都是在httpd.conf文件中修改。 主站点的配置(基本配置) (1) 基本配置: Serv...

php中ob(Output Buffer 输出缓冲)函数使用方法

来自:http://bbs.phome.net/ShowThread/?threadid=9247&forumid=2  在PHP编程中,  我们经...

php使用timthumb生成缩略图的方法

本文实例讲述了php使用timthumb生成缩略图的方法。分享给大家供大家参考,具体如下: 生成缩列图有二种方式: 一、提前生成好,供调用 缩列图常规做法是,开始根据网站中的图片规格,要...

php利用递归实现删除文件目录的方法

直接删除目录,如果是空目录是可以删除,如果不是空目录,这时候只能先删除目录里面的文件,然后再删除目录。我封装了个删除函数,然后直接调用这个函数。喜欢的可以直接拿去用,编码是gbk的,使用...