【转】PHP用GD库生成高质量的缩略图片示例代码

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?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) 代码如下:

1
2
3
4
5
6
7
8
9
10
<?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>

郑州好的男科医院:http://www.ytsgnk.com/郑州看男科医院专业:http://www.ytsgnk.com/郑州同济医院男科咨询预约:http://www.ytsgnk.com/郑州看男科多少钱:http://www.ytsgnk.com/郑州男科医院哪家好:http://www.ytsgnk.com/郑州割包皮医院:https://yyk.familydoctor.com.cn/12248/

猜你喜欢

转载自blog.csdn.net/qq_42606051/article/details/80966160