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

yipeiwu_com6年前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的一个登录的类 [推荐]

PHP代码: <? /* * 名称:CnkknD PHP Login Class * 描述:PHP用于登录的类,基于MySQL *...

PHP实现下载断点续传的方法

本文实例讲述了PHP实现下载断点续传的方法。分享给大家供大家参考。 具体实现代码如下: 复制代码 代码如下:<?php /*  * PHP下载断点续传 &nbs...

那些年我们错过的魔术方法(Magic Methods)

PHP 对象的一个优势是可以使用魔术方法,这些方法可以不需要修改外部代码而重写一个类的默认行为,这使得PHP 语法有更少的冗余性和更具有扩展性。这些方法很好识别,他们都是以双下划线(__...

PHP针对redis常用操作实例详解

本文实例讲述了PHP针对redis常用操作。分享给大家供大家参考,具体如下: /*1.Connection*/ $redis = new Redis(); $redis->co...

PHP中查询SQL Server或Sybase时TEXT字段被截断的解决方法

Author: Wenlong Wu 一、针对MS SQL SERVER数据库    有两种解决方案,如下:    修改php.ini来实现: 打开php.ini,可看到mssql.te...