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给图片添加文字水印方法汇总

1: 面向过程的编写方法 //指定图片路径 $src = '001.png'; //获取图片信息 $info = getimagesize($src); //获取图片扩展名 $typ...

PHP封装的XML简单操作类完整实例

本文实例讲述了PHP封装的XML简单操作类。分享给大家供大家参考,具体如下: xml_dom.php封装类文件: <?php /** * Class xml_dom...

完美解决PHP中文乱码

一.首先是PHP网页的编码 1. php文件本身的编码与网页的编码应匹配 a. 如果欲使用gb2312编码,那么php要输出头:header(“Content-Type: text/ht...

浅谈php中fopen不能创建中文文件名文件的问题

之前网页的chartset用的是utf-8,文件也用utf-8,然后用fopen()创建一个中文文件名的文件时问题就出来了,文件名都是乱 码! 查看了很多文档试了不少方法都解决不了,本来...

php及codeigniter使用session-cookie的方法(详解)

1、读写cookie <1>原生 setcookie('name','value',time) 设置失败,没有正常写入浏览器,测试失败,原因未知 <2>...