php显示图片缩略图,PHP生成缩略图的实现

PHP令我们惊喜的就是在图形图象处理方面要忧于ASP,用GD库PHP就可以轻松的实现缩略图。这一篇文章我们的目的就是用GD来生成缩略图,PHP可以把缩略图直接生成输送到浏览器也可以以文件的形式把其存储到硬盘当中。

在生成缩略图的过程当中我们需要用到GD库当中的几个函数:

getimagesize(string filename [,array var])),取得图像的信息,返回值是一人array,包括几项信息$var[0]----返回图像的width,$var[1]----返回height,[2]返回图像文件的type,[4]返回的是与当中的wdith,height有关的width="",height=""信息。

imageX(resource image)

imageY(resource image)  返回图像的宽和高

imagecopyresized(des img,src img,int des_x,int des_y,int src_x,int src_y,int des_w,int des_h,int src_w,int src_y)  复制并截取区域图像

imagecreatetruecolor(int width,int height)  创建一个真彩图

imagejpeg(resource image)

下面就是Code:

# Constants

define(IMAGE_BASE, '/var/www/html/mbailey/images');

define(MAX_WIDTH, 150);

define(MAX_HEIGHT, 150);

# Get image location

$image_file = str_replace('..', '', $_SERVER['QUERY_STRING']);

$image_path = IMAGE_BASE . "/$image_file";

# Load image

$img = null;

$ext = strtolower(end(explode('.', $image_path)));

if ($ext == 'jpg' || $ext == 'jpeg') {

$img = @imagecreatefromjpeg($image_path);

} else if ($ext == 'png') {

$img = @imagecreatefrompng($image_path);

# Only if your version of GD includes GIF support

} else if ($ext == 'gif') {

$img = @imagecreatefrompng($image_path);

}

# If an image was successfully loaded, test the image for size

if ($img) {

# Get image size and scale ratio

$width = imagesx($img);

$height = imagesy($img);

$scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);

# If the image is larger than the max shrink it

if ($scale < 1) {

$new_width = floor($scale*$width);

$new_height = floor($scale*$height);

# Create a new temporary image

$tmp_img = imagecreatetruecolor($new_width, $new_height);

# Copy and resize old image into new image

imagecopyresized($tmp_img, $img, 0, 0, 0, 0,

$new_width, $new_height, $width, $height);

imagedestroy($img);

$img = $tmp_img;

}

}

# Create error image if necessary

if (!$img) {

$img = imagecreate(MAX_WIDTH, MAX_HEIGHT);

imagecolorallocate($img,0,0,0);

$c = imagecolorallocate($img,70,70,70);

imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);

imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);

}

# Display the image

header("Content-type: image/jpeg");

imagejpeg($img);

?>

我们把上面的Code存储为test.php,然后通过test.php?image name的形式来访问,结果会让你惊喜的,因为在这里你看到了PHP的优点,它可以让ASP相形见绌。

上面的这段代码当中我们通过end(explode(".",$image_path)来取得文件的扩展名,但是我感觉还是不理想。这样是能够取得文件的类型的,因为end()函数会跳到本array的最后一个单元,但是如果我们采用getimagesize()会取得更为强大的专门针对于图像文件的类型。

本程序显示的缩略图是限制宽高都在150内,然后用min()函数来取得它们比值的最小值来计算缩略图的宽和高,并且通过一系列的GD库函数来取得相应的信息,并且呈现给浏览器,当然你也可以写到你所使用的硬盘当中。

好了,这就是PHP的缩略图功能,大家觉得有什么好的意见可以多多拍砖!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值