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>

相关文章

php7基于递归实现删除空文件夹的方法示例

本文实例讲述了php7基于递归实现删除空文件夹的方法。分享给大家供大家参考,具体如下: php版本7.0.4 代码如下: <?php $path = 'd:/'; rm...

组合算法的PHP解答方法

题目:组合算法:有一个数组a,有N 个元素,现在要求从中找出含有任意元素的所有组合个数。 解答:先看规律吧: 假设这个数组为array(1,2,3,4,5)那么M=5; 可能出现的组合为...

php实现字符串首字母大写和单词首字母大写的方法

本文实例讲述了php实现字符串首字母大写和单词首字母大写的方法。分享给大家供大家参考。具体分析如下: ucfirst可以对字符串首字母进行大小,ucwords可以对字符串中每个单词的首字...

php的4种常用运行方式详解

php的4种常用运行方式:CGI、FastCGI、APACHE2HANDLER、CLI。 1、CGI CGI即通用网关接口(common gatewag interface),它是一...

PHP实现简单ajax Loading加载功能示例

本文实例讲述了PHP实现简单ajax Loading加载功能。分享给大家供大家参考,具体如下: var xmlHttp; function createXmlHttpReq() {...