php生成缩略图
phpcmsv9教程:thumb(缩略图)函数说明

phpcmsv9教程:thumb(缩略图)函数说明打开phcmsc/libs/functions/global.func.php⽂件,找到如下代码:/*** ⽣成缩略图函数* @param $imgurl 图⽚路径* @param $width 缩略图宽度* @param $height 缩略图⾼度* @param $autocut 是否⾃动裁剪默认裁剪,当⾼度或宽度有⼀个数值为0是,⾃动关闭* @param $smallpic ⽆图⽚是默认图⽚路径*/function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {global $image;$upload_url = pc_base::load_config('system','upload_url');$upload_path = pc_base::load_config('system','upload_path');if(empty($imgurl)) return IMG_PATH.$smallpic;$imgurl_replace= str_replace($upload_url, '', $imgurl);if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);if($width>=$width_t || $height>=$height_t) return $imgurl;$newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;if(!is_object($image)) {pc_base::load_sys_class('image','','0');$image = new image(1,0);}return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;}此函数类似php⼿册的表现形式为:string thumb( string $imgurl, [int $width = 100], [int $height = 100], [int $autocut = 1], [string $smallpic = 'images/nopic_small.gif'] )功能:调⽤缩略图参数:string $imgurl:图⽚地址int $width:图⽚宽度,可选参数,默认为100int $height:图⽚⾼度,可选参数,默认为100int $autocut:是否⾃动裁切,可选参数,默认为1,为0时,将只等⽐压缩,可能出现图⽚变形string $smallpic:⽆图⽚时显⽰的⼩图⽚地址,可选参数,默认为 images/nopic_small.gif⽰例:{thumb($r[thumb], 160, 100,0)}解析:调⽤缩略图:{thumb(图⽚路径,宽为160,⾼为100,0为等⽐压缩)}---------------------作者:buzhang1314来源:CSDN原⽂:https:///buzhang1314/article/details/50675119版权声明:本⽂为博主原创⽂章,转载请附上博⽂链接!。
php生成图片缩略图的方法

php生成图片缩略图的方法php生成图片缩略图的方法虽然在HTML中可以通过指定图片的宽度和高度来随意缩放图片,但是这种方法不会减少图片的像素数目。
图形文件的尺寸没有改变,当然也不会加快图片下载的速度了。
当然也可以手动通过图形软件生成图片的缩略图,但对于大量的图片展示来说,这个工作量将十分巨大。
为此微缩图的自动生成程序就被设计出来了。
PHP中提供的imagecopyresized函数就可以用来生成真正的缩赂图片。
该函数的标推语法如下:语法:int imagecopyresized(int dst_im,int src_im,int dstX,int dstY,int srcX,int srcY,int dstW,int dstH,int srcW,int srcH);返回值:整数函数种类:图形处理内容说明:本函数可复制新图,并重新调整图片的大小尺寸。
参数都是目的在前,来源在后。
参数dst im及src_im为图片的handle。
参数dstX、dstY、srcX、srcY分别为目的及来源的坐标。
参数dstW、dstH、srcW、srcH分别为来源及目的的宽及高,欲调整的新图的尺寸就在这儿配置。
下面举个例子来说明这个函数的用法,对应的程序thumb.php如程序清单12—5所示。
程序清单12—5 thumb.php复制代码代码如下:<?// 本函数从源文件取出图像,设定成指定大小,并输出到目的文件// 源文件格式:gif,jpg,png// 目的文件格式:gif// $srcFile:源文件// $dstFile: 目标文件// $dstW:目标图片宽度// $dstH:目标文件高度function makethumb($srcFile,$dstFile,$dstW,$dstH){$data = GetImageSize($srcFile,&$info);switch ($data[2]){case 1:$imgsrc = @ImageCreateFromGIF($srcFile);break;case 2:$imgsrc = @ImageCreateFromJPEG($srcFile);break;case 3:$imgsrc = @ImageCreateFromPNG($srcFile);break;}$srcW = ImageSX($imgsrc);$srcH = ImageSY($imgsrc);$ni = ImageCreate($dstW,$dstH);ImageCopyResized($ni,$imgsrc,0,0,0,0,$dstW,$dstH,$srcW,$ srcH);Imagegif($ni,$dstFile);// 如果需要输出到浏览器,那么将上一句改为 ImageJpeg($ni);// 如果需要其他格式的图片,改动最后一句就可以了}>在这个例子中,首先通过getimagesize()函数获得源图片的`情况,再用 imagecreatefromgif()、imagecreatefromjpeg()或imagecreatefrompng()创建一个源位图$imgsrc,然后用imagecreate()函数创建一个目标位图,其长、宽各是源位图的一半。
使用PHP扩展php imagick对图片改变大小、旋转、锐化、减色或增加特效

使用PHP扩展php_imagick对图片改变大小、旋转、锐化、减色或增加特效php_imagick是PHP对图片处理的一个扩展包,可以完成对图片改变大小、旋转、锐化、减色或增加特效等操作。
一、windows下安装Imagick扩展:1、下载 ImageMagick并安装http://image_/image_magick/binaries/ImageMagick-6.6.2-10-Q16-windows -dll.exe2、下载php_imagick.dll/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/ vc9_nts/php_imagick.dll如果你用的是线程安全的php,请下载/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/vc9_zts/php_imagick.dll3、设置在php.ini中添加extension=php_imagick.dll ,重启web server二、linux下安装Imagick扩展:1.yum安装ImageMagickyum install ImageMagick ImageMagick-devel2.测试是否安装成功convert -version3.安装imagick扩展wget /get/imagick-3.1.0RC2.tgztar xzvf imagick-3.1.0RC2.tgzcd imagick-3.1.0RC2phpize./configuremakemake install4.编辑php.ini文件,在文件末尾添加如下代码extension=imagick.so5. 重新启动apache服务器service httpd restart三、案例1. 边框处理//by header('Content-type: image/jpeg');$image = new Imagick('test.jpg');$color=new ImagickPixel();$color->setColor("rgb(220,220,220)");$image->borderImage($color,5,4);$image->blurImage(5,5,imagick::CHANNEL_GREEN);echo $image;(PS:php Q扣峮:276167802,验证:wk)2.生成缩略图//by header('Content-type: image/jpeg');$image = new Imagick('test.jpg');$image->thumbnailImage(50, 0);echo $image;来源:清源教育。
php字符串分割函数用法实例

explode(substring, string)
explode函数通过子字符串进行分割,效率比split要高 split函数语法如下
split(pattern, string)
split通过正则表达式对字符串进行分割,效率相对explode要低,但是功能强大
<?php $list = explode("_","php_strting_function.html"); print("explode() returns:\n"); print_r($list); $list = split("[_.]","php_strting_function.html"); print("split() returns:\n"); print_r($list); ?>
输出结果如下:
explode() returns: Array ( [0] => php [1] => strting [2] => function.html )
split() returns: Array ( [0] => php [1] => strting [2] => function [3] => html )
希望本文所述对大家的php程序设计有所帮助。
这篇文章主要介绍了php实现可添加水印与生成缩略图的图片处理工具类涉及php针对图片的显示保存压缩水印等相关操作技巧需要的朋友可以参考下
php字 符 串 分 割 函 数 用 法 实 例
本文实例讲述了php字符串分割函数用法。分享给大家供大家参考。具体分析如下:
基于PHP技术实现图片缩略图循环播放功能

I b等服务器 上。应 用 P P的网 页与常规 的 HT I We S H ML页面并 无二致 , 可 以直 接在 HT 你 ML文件 里 写入 简单 的脚本 , 一点 与 这
iart a s i 非常相似 。不 同的是 , HP不依赖 于浏 览器 , v cp P 是服务 器端 的语 言, j acit 而 a sr 却是 一种客 户端 的嵌在 H ML中的语 言。 v p T P HP作 为一项优秀 的服务器 端技术 , 可 以利用 它创建 动态的 We 你 b页面、 处理 图片或者 更复杂的交互 式应用 系统。在 实际 的网站
中图分类号 : P 1 T 32
文献标识码 : A
D :03 6  ̄i n1 0 —9 02 1.5 3 OI 1. 9 .s . 36 7 .020 . 5 9 s 0 0
Ba e n P s d o HP Te h o o y t h e e I g u n is Lo p Fu c i n c n l g o Ac i v ma e Th mb a l o n to
sd n u g . i a a c i t sa cin l c i e l g a e wh l J v S r l t o k i HTM L ln u g . HP a o d s r e c n l g , o a s t o c e t y a c a e p i e b n g a e P sa g o e rt h o o y y u c n u ei t r ae a d n mi a v e We a e , ma e rmo e c mp e n e a t e a p ia in s se : n t e a t a b st e i n o r e i g s o t n la o i b p g s i g so r o lx it r c i p l t y t m I h c u l v c o we i d sg ,s u c ma e fe e d t mme s e ne sz , b a e d s ly s e d i o so h w o r e p cu e a t ma ia l o r s e t a t , sas u n i i t e e p e ie we p g ip a p e t lw, o a s u c it r u o t l c mp e s d i o Xio u i lo a t mb al s o l t o l so c y n h , p it r se h a ep o e sn c n l g , h sp p ri t d c d b x mp eu i g P c n l g c iv h mb a l e ea i n n e e td i t e i g r c s i g t h o o y t i a e r u e y e a l sn HP t h o o y t a h e e at u n i g n r t n m e n o e o o p o e s a dh w ep g eW e l me t t n ag o p o t u n i p a b c fe t r c s , n o t a e i t b i e n ai r u f h mb a l ly a k e c . h nh mp o
Swoft图片上传与处理

Swoft图⽚上传与处理上传在Swoft下通过\Swoft\Http\Message\Server\Request -> getUploadedFiles()['image']⽅法可以获取到⼀个 Swoft\Http\Message\Upload\UploadedFile 对象或者对象数组(取决于上传时字段是image还是image[])打印改对象输出:object(Swoft\Http\Message\Upload\UploadedFile)#1813 (6) {["clientFilename":"Swoft\Http\Message\Upload\UploadedFile":private]=>string(25) "蒙太奇配置接⼝.txt"["clientMediaType":"Swoft\Http\Message\Upload\UploadedFile":private]=>string(10) "text/plain"["error":"Swoft\Http\Message\Upload\UploadedFile":private]=>int(0)["tmpFile":"Swoft\Http\Message\Upload\UploadedFile":private]=>string(55) "/var/www/swoft/runtime/uploadfiles/swoole.upfile.xZyq0d"["moved":"Swoft\Http\Message\Upload\UploadedFile":private]=>bool(false)["size":"Swoft\Http\Message\Upload\UploadedFile":private]=>int(710)}都是私⽤属性,⽆法访问,但是可以通过对应⽅法访问到getClientFilename() //得到⽂件原名称getClientMediaType() //得到⽂件类型getSize() //获取到⽂件⼤⼩通过⽅法moveTo() //将⽂件从临时位置转移到⽬录上⾯⽅法返回为NULL,在移动⽂件到指定位置时最好判断⼀下⽂件夹是否存在,不存在创建图⽚处理借助⼯具完成ubuntu下⼀键安装I. 安装ImageMagicksudo apt-get install imagemagickII. 安装imagemagick 的lib 供php调⽤sudo apt-get install libmagick++-devIII. 调⽤当前的pecl安装imagickpecl install imagickIV. 修改php.ini.重启nginx服务器在php.ini中添加: extension = imagick.so在安装完成后修改完 /etc/php/7.0/cli/php.ini 后发现 phpinfo 页⾯打印出来没有出现下⾯信息,于是⼜修改了/etc/php/7.0/fpm/php.ini 才出现下⾯信息安装 Intervention Imagecomposer require intervention/image安装完成后可以直接在页⾯useuse Intervention\Image\ImageManager;$manager = new ImageManager(array('driver' => 'imagick'));//宽缩⼩到300px,⾼⾃适应$thumb = $manager->make($path)->resize(300, null, function ($constraint) { $constraint->aspectRatio();});$thumb->save($path);完整代码namespace App\Controllers\Api;use Intervention\Image\ImageManager;use Swoft\Http\Message\Server\Request;use Swoft\Http\Message\Upload\UploadedFile;use Swoft\Http\Server\Exception\NotAcceptableException;use Swoft\Http\Server\Bean\Annotation\Controller;use Swoft\Http\Server\Bean\Annotation\RequestMapping;use Swoft\Http\Server\Bean\Annotation\RequestMethod;class FileController{//图⽚可接受的mime类型private static$img_mime = ['image/jpeg','image/jpg','image/png','image/gif']; /*** ⽂件上传* @RequestMapping(route="image",method=RequestMethod::POST)*/public static function imgUpload(Request $request){$files = $request->getUploadedFiles()['image'];if(!$files){throw new NotAcceptableException('image字段为空');}if(is_array($files)){$result = array();foreach ($files as$file){self::checkImgFile($file);$result[] = self::saveImg($file);}}else{self::checkImgFile($files);return self::saveImg($files);}}/*** 保存图⽚* @param UploadedFile $file*/protected static function saveImg(UploadedFile $file){$dir = alias('@upload') . '/' . date('Ymd');if(!is_dir($dir)){@mkdir($dir,0777,true);}$ext_name = substr($file->getClientFilename(), strrpos($file->getClientFilename(),'.'));$file_name = time().rand(1,999999);$path = $dir . '/' . $file_name . $ext_name;$file->moveTo($path);//修改移动后⽂件访问权限,⽂件默认没有访问权限@chmod($path,0775);//⽣成缩略图$manager = new ImageManager(array('driver' => 'imagick'));$thumb = $manager->make($path)->resize(300, null, function ($constraint) {$constraint->aspectRatio();});$thumb_path = $dir. '/' . $file_name . '_thumb' .$ext_name;$thumb->save($dir. '/' . $file_name . '_thumb' .$ext_name);@chmod($thumb_path,0775);return ['url' => explode(alias('@public'),$path)[1],'thumb_url' => explode(alias('@public'),$thumb_path)[1]];}/*** 图⽚⽂件校验* @param UploadedFile $file* @return bool*/protected static function checkImgFile(UploadedFile $file){if($file->getSize() > 1024*1000*2){throw new NotAcceptableException($file->getClientFilename().'⽂件⼤⼩超过2M'); }if(!in_array($file->getClientMediaType(), self::$img_mime)){throw new NotAcceptableException($file->getClientFilename().'类型不符');}return true;}}使⽤FileController::imgUpload($request);说明当前保存⽂件路径为 alias("@upload"),需要在 /config/define.php ⼿动填上该路径$aliases = ['@root' => BASE_PATH,'@env' => '@root','@app' => '@root/app','@res' => '@root/resources','@runtime' => '@root/runtime','@configs' => '@root/config','@resources' => '@root/resources','@beans' => '@configs/beans','@properties' => '@configs/properties','@console' => '@beans/console.php','@commands' => '@app/command','@vendor' => '@root/vendor','@public' => '@root/public', //public⽬录,也是nginx设置站点根⽬录 '@upload' => '@public/upload' //上传⽬录];Swoft 不提供静态资源访问,可以使⽤nginx托管配置nginxvim /etc/nginx/sites-avaiable/defaultserver {listen 80 default_server;listen [::]:80 default_server;# 域名设置server_name ;#设置nginx根⽬录root /var/www/html/swoft/public;# 将所有⾮静态请求转发给 Swoft 处理location / {proxy_set_header X-Real-IP $remote_addr;proxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Connection "keep-alive";proxy_pass http://127.0.0.1:9501;}location ~ \.php$ {proxy_pass http://127.0.0.1:9501;}# 静态资源使⽤nginx托管location ~* \.(js|map|css|png|jpg|jpeg|gif|ico|ttf|woff2|woff)$ {expires max;}}。
c#生成图片缩略图的类(2种实现思路)

c#⽣成图⽚缩略图的类(2种实现思路)复制代码代码如下:/**//// <summary>/// ⽣成缩略图/// </summary>/// <param name="originalImagePath">源图路径(物理路径)</param>/// <param name="thumbnailPath">缩略图路径(物理路径)</param>/// <param name="width">缩略图宽度</param>/// <param name="height">缩略图⾼度</param>/// <param name="mode">⽣成缩略图的⽅式</param>public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) {Image originalImage = Image.FromFile(originalImagePath);int towidth = width;int toheight = height;int x = 0;int y = 0;int ow = originalImage.Width;int oh = originalImage.Height;switch (mode){case "HW"://指定⾼宽缩放(可能变形)break;case "W"://指定宽,⾼按⽐例toheight = originalImage.Height * width/originalImage.Width;break;case "H"://指定⾼,宽按⽐例towidth = originalImage.Width * height/originalImage.Height;break;case "Cut"://指定⾼宽裁减(不变形)if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight){oh = originalImage.Height;ow = originalImage.Height*towidth/toheight;y = 0;x = (originalImage.Width - ow)/2;}else{ow = originalImage.Width;oh = originalImage.Width*height/towidth;x = 0;y = (originalImage.Height - oh)/2;}break;default :break;}//新建⼀个bmp图⽚Image bitmap = new System.Drawing.Bitmap(towidth,toheight);//新建⼀个画板Graphics g = System.Drawing.Graphics.FromImage(bitmap);//设置⾼质量插值法g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置⾼质量,低速度呈现平滑程度g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//清空画布并以透明背景⾊填充g.Clear(Color.Transparent);//在指定位置并且按指定⼤⼩绘制原图⽚的指定部分g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),new Rectangle(x, y, ow,oh),GraphicsUnit.Pixel);try{//以jpg格式保存缩略图bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);}catch(System.Exception e){throw e;}finally{originalImage.Dispose();bitmap.Dispose();g.Dispose();}}关键⽅法Graphics.DrawImage见ms-help://FrameworkSDKv1.1.CHS/cpref/html/frlrfsystemdrawinggraphicsclassdrawimagetopic11.htm 4个重载⽅法,有直接返回Image对象的,有⽣成缩略图,并且保存到指定⽬录的!复制代码代码如下:using System.IO;using System.Drawing;using System.Drawing.Imaging;/// <summary>/// 图⽚处理类/// 1、⽣成缩略图⽚或按照⽐例改变图⽚的⼤⼩和画质/// 2、将⽣成的缩略图放到指定的⽬录下/// </summary>public class ImageClass{public Image ResourceImage;private int ImageWidth;private int ImageHeight;public string ErrMessage;/// <summary>/// 类的构造函数/// </summary>/// <param name="ImageFileName">图⽚⽂件的全路径名称</param>public ImageClass(string ImageFileName){ResourceImage=Image.FromFile(ImageFileName);ErrMessage="";}public bool ThumbnailCallback(){return false;}/// <summary>/// ⽣成缩略图重载⽅法1,返回缩略图的Image对象/// </summary>/// <param name="Width">缩略图的宽度</param>/// <param name="Height">缩略图的⾼度</param>/// <returns>缩略图的Image对象</returns>public Image GetReducedImage(int Width,int Height){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ReducedImage=ResourceImage.GetThumbnailImage(Width,Height,callb,IntPtr.Zero);return ReducedImage;}catch(Exception e){ErrMessage=e.Message;return null;}}/// <summary>/// ⽣成缩略图重载⽅法2,将缩略图⽂件保存到指定的路径/// </summary>/// <param name="Width">缩略图的宽度</param>/// <param name="Height">缩略图的⾼度</param>/// <param name="targetFilePath">缩略图保存的全⽂件名,(带路径),参数格式:D:Images ilename.jpg</param> /// <returns>成功返回true,否则返回false</returns>public bool GetReducedImage(int Width,int Height,string targetFilePath){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ReducedImage=ResourceImage.GetThumbnailImage(Width,Height,callb,IntPtr.Zero);ReducedImage.Save(@targetFilePath,ImageFormat.Jpeg);ReducedImage.Dispose();return true;}catch(Exception e){ErrMessage=e.Message;return false;}}/// <summary>/// ⽣成缩略图重载⽅法3,返回缩略图的Image对象/// </summary>/// <param name="Percent">缩略图的宽度百分⽐如:需要百分之80,就填0.8</param>/// <returns>缩略图的Image对象</returns>public Image GetReducedImage(double Percent){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ImageWidth=Convert.ToInt32(ResourceImage.Width*Percent);ImageHeight=Convert.ToInt32(ResourceImage.Width*Percent);ReducedImage=ResourceImage.GetThumbnailImage(ImageWidth,ImageHeight,callb,IntPtr.Zero);return ReducedImage;}catch(Exception e){ErrMessage=e.Message;return null;}}/// <summary>/// ⽣成缩略图重载⽅法4,返回缩略图的Image对象/// </summary>/// <param name="Percent">缩略图的宽度百分⽐如:需要百分之80,就填0.8</param>/// <param name="targetFilePath">缩略图保存的全⽂件名,(带路径),参数格式:D:Images ilename.jpg</param> /// <returns>成功返回true,否则返回false</returns>public bool GetReducedImage(double Percent,string targetFilePath){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ImageWidth=Convert.ToInt32(ResourceImage.Width*Percent);ImageHeight=Convert.ToInt32(ResourceImage.Width*Percent);ReducedImage=ResourceImage.GetThumbnailImage(ImageWidth,ImageHeight,callb,IntPtr.Zero); ReducedImage.Save(@targetFilePath,ImageFormat.Jpeg);ReducedImage.Dispose();return true;}catch(Exception e){ErrMessage=e.Message;return false;}}}。
比较基础的php面试题及答案-基础题部分

$lifeTime = 小时 * 秒;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
方法3:setcookie() and session_set_cookie_params($lifeTime);
mysql_query(”BEGIN”);
mysql_query(”INSERT INTO customerinfo (name) VALUES (’$name1′)”;
mysql_query(”SELECT * FROM `orderinfo` where customerid=”.$id”);
18、有一个网页地址, 比如PHP开发资源网主页: /index.html,如何得到它的内容?($1分)
答:方法1(对于PHP5及更高版本):
$readcontents = fopen(”/index.html”, “rb”);
答:确认服务器硬件是否足够支持当前的流量,数据库读写分离,优化数据表,
程序功能规则,禁止外部的盗链,控制大文件的下载,使用不同主机分流主要流量
15、用PHP写出显示客户端IP与服务器IP的代码1分)
答:打印客户端IP:echo $_SERVER[‘REMOTE_ADDR’]; 或者: getenv(’REMOTE_ADDR’);
b.提取所有没有订单客户:SELECT FROM customerinfo WHERE customerid NOT in(SELECT customerid FROM orderinfo)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
PHP令我们惊喜的就是在图形图象处理方面要忧于ASP,用GD库PHP就可以轻松的实现缩略图。
这一篇文章我们的目的就是用GD来生成缩略图,PHP可以把缩略图直接生成输送到浏览器也可以以文件的形式把其存储到硬盘当中。
在生成缩略图的过程当中我们需要用到GD库当中的几个函数:
getimagesize(string filename [,array var])),取得图像的信息,返回值是一人array,包括几项信息$var[0]----返回图像的width,$var[1]----返回 height,[2]返回图像文件的type,[4]返回的是与<img src="">当中的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:
<?php
# 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的缩略图功能,大家觉得有什么好的意见可以多多拍砖!。