首页 > php图像处理 > php gd库函数生成高清缩略图程序

php gd库函数生成高清缩略图程序

gd库是php教程中一个处理图像的专用库,他可以方便快捷的处理大多数据处理,它提供了大量的图片处理函数,下面我们就利用gd库的函数来生成缩略图.

测试代码如下:

<?php
include ('resizeimage.php');
if (!emptyempty($_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>

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);
    }
}
?>


本文链接:http://www.phprm.com/tuxiang/fs4438.html

收藏随意^^请保留教程地址.

标签:php gd库函数 缩略图程序

相关文章

发表留言