PHP(16) 生成缩略图
在PHP中实现生成缩略图的操作是非常简单的,其主要依靠的函数是p_w_picpathcopyresampled或p_w_picpathcopyresized.其区别在于前者将重新采样!这里我们主要采用p_w_picpathcopyresampled
Imagecopyresampled函数的语法结构是:
p_w_picpathcopyresampled ( resource $目标图像资源 , resource $源图像资源 , int $目标图像X轴, int 目标图像Y轴 , int $源图像X轴 , int $源图像Y轴 , int $目标图像宽度 , int $目标图像高度 , int $源图像宽度 , int $源图像高度 );
这个函数的参数较多,但是理解起来还是非常简单的!
其含义是:从某图像(源图像)的某个位置(X,Y)起复制指定区域(width,height)后,粘贴到另外一个图像(目标图像)的某个位置(X,Y)起的指定区域(width,height)。
那么,我们就从这个函数来分析一下,我们应该做的准备工作。
第一:目标图像,而且目标图像的数据是来源于源图像的,所以,我们只需要准备一张空图像就可以了,所以…
$destImg = p_w_picpathcreatetruecolor(width,height);
但关键问题是,目标图像的资源的宽度和高度没有办法事先固定!而且我们的目的是生成原图的缩略图,所以,如果我们知道了源图像的宽度和高度后,那么就可以确定目标图像的宽度和高度了!好了,干活!
第二步:获取源图像的宽度和高度---getp_w_picpathsize
getp_w_picpathsize函数的语法是:
$变量名称 = getp_w_picpathsize(“文件的位置及全称”);
所以,我们只需要知道源图像的位置及全称就可以了,好了,我们先固定一个文件吧!
$filename = “./01.jpg”;
list($srcWidth,$srcHeight) = getp_w_picpathsize($filename);
现在好了,源图像的尺寸已经知道了,那么,第一步也就可以确定了,而且,现在我们发现第二步和第一步的顺序也必须调换一下!其代码如下:
$filename = “./01.jpg”;
$scalePercent = 0.5;
list($srcWidth,$srcHeight,$imgType) = getp_w_picpathsize($filename);
$destWidth = ceil($srcWidth * $scalePercent);
$destHeight = ceil($srcHeight * $scalePercent);
经过以上的分析,p_w_picpathcopyresampled函数的很多参数就可以确定下了,现在就变成了:
p_w_picpathcopyresampled($destImg,$源图像资源,0,0,0,0,$destWidth,$destHeight,$srcWidth,$srcHeight);
那么现在的关键问题是:如何将源图像变量资源(resource)类型的变量!
在GD函数库中,p_w_picpathcreate、p_w_picpathcreatetruecolor是创建一个空白的图像资源;而p_w_picpathcreatefromgif、p_w_picpathcreatefromjpeg、p_w_picpathcreatefrompng,则是将已经存在的图像文件变成图像资源,好了,干活吧!
$srcImage = p_w_picpathcreatefromjpeg($filename);
好了,现在所有的参数都确定好了!如下
好了,现在所有的参数都确定好了!如下
p_w_picpathcopyresampled($destImg,$srcImg,0,0,0,0,$destWidth,$destHeight,$srcWidth,$srcHeight);
最后,只剩下一个问题,将缩略图生成文件存储到磁盘上就OK了!
Imagejpeg($destImg,”./small.jpg”);
Imagedestroy($srcImg);
Imagedestroy($destImg);
最后的代码如下:
<?php
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
$filename
= "./01.jpg";
$scalePercent
= 0.5;
list
(
$srcWidth
,
$srcHeight
)
= getp_w_picpathsize($filename);
$destWidth
= ceil($srcWidth * $scalePercent);
$destHeight
= ceil($srcHeight * $scalePercent);
$destImg
= p_w_picpathcreatetruecolor($destWidth,$destHeight);
$srcImg
= p_w_picpathcreatefromjpeg($filename);
p_w_picpathcopyresampled(
$destImg
,
$srcImg
,
0
,
0
,
0
,
0
,
$destWidth
,
$destHeight
,
$srcWidth
,
$srcHeight
);
p_w_picpathjpeg(
$destImg
,
"small.jpg"
);
p_w_picpathdestroy(
$srcImg
);
p_w_picpathdestroy(
$destImg
);
?>
当然现在的这个功能还有一些局限性,例如源文件不能固定、没有添加水印效果等,这些,我会在以后的博文中继续给大家作介绍!
转载于:https://blog.51cto.com/pangdou/239603