php图像处理(缩放、剪裁、缩放、翻转、旋转、透明、锐化)

 更新时间:2016年11月25日 16:56  点击:2511
本文章来给各同学总结了一些常用的图像处理函数,包括有缩放、剪裁、缩放、翻转、旋转、透明、锐化功能,大家可参考参考。


注意事项:如果要使用php gd处理我们需要开启gd库


Windows下开启PHP的GD库支持

找到php.ini,打开内容,找到:

;extension=php_gd2.dll

把最前面的分号“;”去掉,再保存即可,如果本来就没有分号,那就是已经开启了。


linux开启GD库


##检测GD库是否安装命令
 php5 -m | grep -i gd
 或者
 php -i | grep -i --color gd
##如未安装GD库,则为服务器安装,方法如下
### 如果是源码安装,则加入参数
 --with-gd
### 如果是debian系的linux系统,用apt-get安装,如下
 apt-get install php5-gd
### 如果是CentOS系的系统,用yum安装,如下
 yum install php-gd
### 如果是suse系的linux系统,用yast安装,如下
 yast -i php5_gd


一、创建图片资源

imagecreatetruecolor(width,height);

imagecreatefromgif(图片名称);

imagecreatefrompng(图片名称);

imagecreatefromjpeg(图片名称);

画出各种图像

imagegif(图片资源,保存路径);

imagepng()

imagejpeg();


二、获取图片属性

imagesx(res//宽度

imagesy(res//高度

getimagesize(文件路径)

返回一个具有四个单元的数组。索引 0 包含图像宽度的像素值,索引 1 包含图像高度的像素值。索引 2 是图像类型的标记:1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM。这些标记与 PHP 4.3.0 新加的 IMAGETYPE 常量对应。索引 3 是文本字符串,内容为“height="yyy" width="xxx"”,可直接用于 IMG 标记。销毁图像资源

imagedestroy(图片资源);


三、透明处理

PNG、jpeg透明色都正常,只有gif不正常

imagecolortransparent(resource image [,int color])//将某个颜色设置成透明色

imagecolorstotal()

imagecolorforindex();

四、图片的裁剪

imagecopyresized()

imagecopyresampled();


五、加水印(文字、图片)

字符串编码转换string iconv ( string $in_charset , string $out_charset , string $str )


六、图片旋转

imagerotate();//制定角度的图片翻转


七、图片的翻转

沿X轴   沿Y轴翻转

八、锐化

imagecolorsforindex()

imagecolorat()

在图片上画图形
 $img=imagecreatefromgif("./images/map.gif");
 $red= imagecolorallocate($img, 255, 0, 0);

 imageline($img, 0, 0, 100, 100, $red);

 imageellipse($img, 200, 100, 100, 100, $red);

 imagegif($img, "./images/map2.gif");

 imagedestroy($img);图片普通缩放

$filename="./images/hee.jpg";

 $per=0.3;

 list($width, $height)=getimagesize($filename);

 $n_w=$width*$per;
 $n_h=$width*$per;

 $new=imagecreatetruecolor($n_w, $n_h);

 $img=imagecreatefromjpeg($filename);
//拷贝部分图像并调整

 imagecopyresized($new, $img,0, 0,0, 0,$n_w, $n_h, $width, $height);
//图像输出新图片、另存为

 imagejpeg($new, "./images/hee2.jpg");

 imagedestroy($new);
 imagedestroy($img);图片等比例缩放、没处理透明色

function thumn($background, $width, $height, $newfile) {
 list($s_w, $s_h)=getimagesize($background);//获取原图片高度、宽度

 if ($width && ($s_w < $s_h)) {
     $width = ($height / $s_h) * $s_w;
 } else {
     $height = ($width / $s_w) * $s_h;
 }

 $new=imagecreatetruecolor($width, $height);

 $img=imagecreatefromjpeg($background);

 imagecopyresampled($new, $img, 0, 0, 0, 0, $width, $height, $s_w, $s_h);

 imagejpeg($new, $newfile);

 imagedestroy($new);
 imagedestroy($img);
}

thumn("images/hee.jpg", 200, 200, "./images/hee3.jpg");gif透明色处理

function thumn($background, $width, $height, $newfile) {
 list($s_w, $s_h)=getimagesize($background);

 if ($width && ($s_w < $s_h)) {
     $width = ($height / $s_h) * $s_w;
 } else {
     $height = ($width / $s_w) * $s_h;
 }

 $new=imagecreatetruecolor($width, $height);

 $img=imagecreatefromgif($background);

 $otsc=imagecolortransparent($img);
 if($otsc >=0 && $otst < imagecolorstotal($img)){//判断索引色
  $tran=imagecolorsforindex($img, $otsc);//索引颜色值

  $newt=imagecolorallocate($new, $tran["red"], $tran["green"], $tran["blue"]);

  imagefill($new, 0, 0, $newt);

  imagecolortransparent($new, $newt);
 }

 imagecopyresized($new, $img, 0, 0, 0, 0, $width, $height, $s_w, $s_h);

 imagegif($new, $newfile);

 imagedestroy($new);
 imagedestroy($img);
}

thumn("images/map.gif", 200, 200, "./images/map3.gif");图片裁剪

function cut($background, $cut_x, $cut_y, $cut_width, $cut_height, $location){

 $back=imagecreatefromjpeg($background);

 $new=imagecreatetruecolor($cut_width, $cut_height);

 imagecopyresampled($new, $back, 0, 0, $cut_x, $cut_y, $cut_width, $cut_height,$cut_width,$cut_height);

 imagejpeg($new, $location);

 imagedestroy($new);
 imagedestroy($back);
}

cut("./images/hee.jpg", 440, 140, 117, 112, "./images/hee5.jpg");图片加水印

文字水印

function mark_text($background, $text, $x, $y){
  $back=imagecreatefromjpeg($background);

  $color=imagecolorallocate($back, 0, 255, 0);

  imagettftext($back, 20, 0, $x, $y, $color, "simkai.ttf", $text);

  imagejpeg($back, "./images/hee7.jpg");

  imagedestroy($back);
 }

 mark_text("./images/hee.jpg", "细说PHP", 150, 250);

//图片水印
function mark_pic($background, $waterpic, $x, $y){
$back=imagecreatefromjpeg($background);
$water=imagecreatefromgif($waterpic);
$w_w=imagesx($water);
$w_h=imagesy($water);
imagecopy($back, $water, $x, $y, 0, 0, $w_w, $w_h);
imagejpeg($back,"./images/hee8.jpg");
imagedestroy($back);
imagedestroy($water);
}
mark_pic("./images/hee.jpg", "./images/gaolf.gif", 50, 200);图片旋转

$back=imagecreatefromjpeg("./images/hee.jpg");

 $new=imagerotate($back, 45, 0);

 imagejpeg($new, "./images/hee9.jpg");图片水平翻转垂直翻转

function turn_y($background, $newfile){
  $back=imagecreatefromjpeg($background);

  $width=imagesx($back);
  $height=imagesy($back);

  $new=imagecreatetruecolor($width, $height);

  for($x=0; $x < $width; $x++){
   imagecopy($new, $back, $width-$x-1, 0, $x, 0, 1, $height);
  }

  imagejpeg($new, $newfile);

  imagedestroy($back);
  imagedestroy($new);
 }

 function turn_x($background, $newfile){
  $back=imagecreatefromjpeg($background);

  $width=imagesx($back);
  $height=imagesy($back);

  $new=imagecreatetruecolor($width, $height);

  for($y=0; $y < $height; $y++){
   imagecopy($new, $back,0, $height-$y-1, 0, $y, $width, 1);
  }

  imagejpeg($new, $newfile);

  imagedestroy($back);
  imagedestroy($new);
 }

 turn_y("./images/hee.jpg", "./images/hee11.jpg");
 turn_x("./images/hee.jpg", "./images/hee12.jpg"); 图片锐化

function sharp($background, $degree, $save){
 $back=imagecreatefromjpeg($background);

 $b_x=imagesx($back);
 $b_y=imagesy($back);

 $dst=imagecreatefromjpeg($background);
 for($i=0; $i<$b_x; $i++){
  for($j=0; $j<$b_y; $j++){
   $b_clr1=imagecolorsforindex($back, imagecolorat($back, $i-1, $j-1));\前一个像素颜色数组
   $b_clr2=imagecolorsforindex($back, imagecolorat($back, $i, $j));\取出当前颜色数组

   $r=intval($b_clr2["red"]+$degree*($b_clr2["red"]-$b_clr1["red"]));\加深
   $g=intval($b_clr2["green"]+$degree*($b_clr2["green"]-$b_clr1["green"]));
   $b=intval($b_clr2["blue"]+$degree*($b_clr2["blue"]-$b_clr1["blue"]));

   $r=min(255, max($r, 0));//限制r范围在0-255之间
   $g=min(255, max($g, 0));
   $b=min(255, max($b, 0));

   if(($d_clr=imagecolorexact($dst, $r, $g, $b))==-1){//等于1不在颜色范围内
    $d_clr=Imagecolorallocate($dst, $r, $g, $b);//创建一个颜色
   }

   imagesetpixel($dst, $i, $j, $d_clr);
  }

 }
 imagejpeg($dst, $save);
 imagedestroy($back);
 imagedestroy($dst);
}

sharp("./images/hee.jpg", 20, "./images/hee13.jpg");十月 26th, 2011No comments yet真诚待 php设计实现和应用验证码类
validationcode.class.php

/* 开发一个验证码类
 *
 * 1. 什么是验证码
 *
 * 2. 验证码的作用
 *
 * 3. 编写验证码类(PHP图像处理)
 *
 * 4. 使用验证码
 *
 *
 */<?php
 class ValidationCode {
  private $width;
  private $height;
  private $codeNum;
  private $image;   //图像资源
  private $disturbColorNum;
  private $checkCode;

  function __construct($width=80, $height=20, $codeNum=4){
   $this->width=$width;
   $this->height=$height;
   $this->codeNum=$codeNum;
   $this->checkCode=$this->createCheckCode();
   $number=floor($width*$height/15);

   if($number > 240-$codeNum){
    $this->disturbColorNum= 240-$codeNum;
   }else{
    $this->disturbColorNum=$number;
   }

  }
  //通过访问该方法向浏览器中输出图像
  function showImage($fontFace=""){
   //第一步:创建图像背景
   $this->createImage();
   //第二步:设置干扰元素
   $this->setDisturbColor();
   //第三步:向图像中随机画出文本
   $this->outputText($fontFace);
   //第四步:输出图像
   $this->outputImage();
  }

  //通过调用该方法获取随机创建的验证码字符串
  function getCheckCode(){
   return $this->checkCode;
  }

  private function createImage(){
   //创建图像资源
   $this->image=imagecreatetruecolor($this->width, $this->height);
   //随机背景色
   $backColor=imagecolorallocate($this->image, rand(225, 255), rand(225,255), rand(225, 255));
   //为背景添充颜色
   imagefill($this->image, 0, 0, $backColor);
   //设置边框颜色
   $border=imagecolorallocate($this->image, 0, 0, 0);
   //画出矩形边框
   imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, $border);
  }

  private function  setDisturbColor(){
   for($i=0; $i<$this->disturbColorNum; $i++){
    $color=imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
    imagesetpixel($this->image, rand(1, $this->width-2), rand(1, $this->height-2), $color);
   }

   for($i=0; $i<10; $i++){
    $color=imagecolorallocate($this->image, rand(200, 255), rand(200, 255), rand(200, 255));
    imagearc($this->image, rand(-10, $this->width), rand(-10, $this->height), rand(30, 300), rand(20, 200), 55, 44, $color);
   }
  }

  private function createCheckCode(){
   $code="23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
   $string='';
   for($i=0; $i < $this->codeNum; $i++){
    $char=$code{rand(0, strlen($code)-1)};
    $string.=$char;
   }

   return $string;
  }

  private function outputText($fontFace=""){
   for($i=0; $i<$this->codeNum; $i++){
    $fontcolor=imagecolorallocate($this->image, rand(0, 128), rand(0, 128), rand(0, 128));
    if($fontFace==""){
     $fontsize=rand(3, 5);
     $x=floor($this->width/$this->codeNum)*$i+3;
     $y=rand(0, $this->height-15);
     imagechar($this->image,$fontsize, $x, $y, $this->checkCode{$i},$fontcolor);
    }else{
     $fontsize=rand(12, 16);
     $x=floor(($this->width-8)/$this->codeNum)*$i+8;
     $y=rand($fontSize+5, $this->height);
     imagettftext($this->image,$fontsize,rand(-30, 30),$x,$y ,$fontcolor, $fontFace, $this->checkCode{$i});
    }
   }
  }

  private function outputImage() {
   if(imagetypes() & IMG_GIF){
    header("Content-Type:image/gif");
    imagepng($this->image);
   }else if(imagetypes() & IMG_JPG){
    header("Content-Type:image/jpeg");
    imagepng($this->image);
   }else if(imagetypes() & IMG_PNG){
    header("Content-Type:image/png");
    imagepng($this->image);
   }else if(imagetypes() & IMG_WBMP){
    header("Content-Type:image/vnd.wap.wbmp");
    imagepng($this->image);
   }else{
    die("PHP不支持图像创建");
   }
  }

  function __destruct(){
   imagedestroy($this->image);
  }
 }code.php

<?php
 session_start();
 include "validationcode.class.php";

 $code=new ValidationCode(80, 20, 4);

 $code->showImage();   //输出到页面中供 注册或登录使用

 $_SESSION["code"]=$code->getCheckCode();  //将验证码保存到服务器中demo.php

<?php
 session_start();
 echo $_POST["code"]."<br>";
 echo $_SESSION["code"]."<br>";

 if(strtoupper($_POST["code"])==strtoupper($_SESSION["code"])){
  echo "ok";
 }else{
  echo "error";
 }
?>
<body>
 <form action="login.php" method="post">
  user:<input type="text" name="usenrame"><br>
  pass:<input type="passowrd" name="pass"><br>

  code: <input type="text" name="code" onkeyup="if(this.value!=this.value.toUpperCase()) this.value=this.value.toUpperCase()"> <img src="code.php" onclick="this.src='code.php?'+Math.random()"><br>

  <input type="submit" name="sub" value="login"><br>
 </form>
</body>


1、画图

验证码,统计图

安装GD库(图片处理库)

■创建一个画布—-创建资源类型——–高度、宽度
■绘制图像
1、制定各种颜色
2、矩形、园、点、线段、扇形、画字(字符、字符串、freetype字体),每一个图像对应一个函数

■输出图像/保存处理好的图像
1、输出各种类型(gif、png、jpeg)

imagegif();
imagepng();
imagegpeg();

■释放资源
<?php
//step 1创建图片资源
$img=imagecreatetruecolor(200,200);
$red=imagecolorallocate($img,255,0,0);
$yellow=imagecolorallocate($img,255,255,0);
$green=imagecolorallocate($img,0,255,0);
$blue=imagecolorallocate($img,0,0,255);
imagefill($img,0,0,$yellow);//颜色填充
//step2画各种图形
imagefilledrectangle($img,10,10,80,80,$red);//画矩形并填充
imagerectangle($img,10,10,80,80,$red));//画矩形不填充,颜色填充

//线段
 imageline($img,0, 0, 200, 200 ,$blue);
 imageline($img,200, 0, 0, 200, $blue);

 //点
 imagesetpixel($img,50, 50 ,$red);
 imagesetpixel($img,55, 50 ,$red);
 imagesetpixel($img,59, 50 ,$red);
 imagesetpixel($img,64, 50 ,$red);
 imagesetpixel($img,72, 50 ,$red);

 //圆
 imageellipse($img, 100, 100, 100, 100,$green);
 //圆
 imagefilledellipse($img, 100, 100, 10, 10,$blue);
边框
//输出图像或保存图像
header("Content-Type:img/gif");
imagegif($img);
//释放资源
imagedestory($img);

画饼状图

//step 1创建图片资源
 $img=imagecreatetruecolor(200, 200);

// $img=imagecreate(200, 200);

 $white=imagecolorallocate($img, 255, 255, 255);
 $gray=imagecolorallocate($img, 0xC0, 0xC0, 0xC0);
 $darkgray=imagecolorallocate($img, 0x90, 0x90, 0x90);
 $navy=imagecolorallocate($img, 0, 0, 0x80);
 $darknavy=imagecolorallocate($img, 0, 0, 0x50);
 $red= imagecolorallocate($img, 0xFF, 0, 0);
 $darkred=imagecolorallocate($img, 0x90, 0, 0);

 imagefill($img, 0, 0, $white);

 //3D效果
 for($i=60; $i>50; $i--){
  imagefilledarc($img, 50, $i,100, 50, -160, 40, $darkgray, IMG_ARC_PIE);
  imagefilledarc($img, 50, $i,100, 50, 40, 75, $darknavy, IMG_ARC_PIE);
  imagefilledarc($img, 50, $i,100, 50, 75, 200, $darkred, IMG_ARC_PIE);
 }
  imagefilledarc($img, 50, $i,100, 50, -160, 40, $gray, IMG_ARC_PIE);
  imagefilledarc($img, 50, $i,100, 50, 40, 75, $navy, IMG_ARC_PIE);
  imagefilledarc($img, 50, $i,100, 50, 75, 200, $red, IMG_ARC_PIE);

 header("Content-Type:image/gif");
 imagegif($img);

 //释放资源
 imagedestroy($img);画文字

<?php

 //step 1创建图片资源
 $img=imagecreatetruecolor(200, 200);

// $img=imagecreate(200, 200);

 $white=imagecolorallocate($img, 255, 255, 255);
 $gray=imagecolorallocate($img, 0xC0, 0xC0, 0xC0);
 $darkgray=imagecolorallocate($img, 0x90, 0x90, 0x90);
 $navy=imagecolorallocate($img, 0, 0, 0x80);
 $darknavy=imagecolorallocate($img, 0, 0, 0x50);
 $red= imagecolorallocate($img, 0xFF, 0, 0);
 $darkred=imagecolorallocate($img, 0x90, 0, 0);

 imagefill($img, 0, 0, $gray);

 imagechar($img, 5, 100, 100, "A", $red);
 imagechar($img, 5, 120, 120, "B", $red);
 imagecharup($img, 5, 60, 60, "C", $red);
 imagecharup($img, 5, 80, 80, "D", $red);

 imagestring($img, 3, 10, 10, "Hello", $navy);
 imagestringup($img, 3, 10, 80, "Hello", $navy);

 imagettftext($img, 25, 60, 150, 150, $red, "simkai.ttf", "##");
 imagettftext($img, 12, -60, 50, 150, $red, "simli.ttf", "##");

 header("Content-Type:image/gif");
 imagegif($img);

 //释放资源
 imagedestroy($img);2、处理原有的图像

生成图形验证码需要使用php GD库来生成,如果你没开户GD库我们需要在php.ini文件找到extension=php_gd2.dll 去掉前面的;就行了,然后重启apache 或iis环境即可。

我们先来检查一下自己的php是不是打开了gd库。

 代码如下 复制代码

<?php
if(extension_loaded('gd')) {
  echo '你可以使用gd<br>';
  foreach(gd_info() as $cate=>$value)
    echo "$cate: $value<br>";
}else
  echo '你没有安装gd扩展';
?>

如果有返回信息就正确可以常用使用了


例1

 代码如下 复制代码

<?php
/**
 * vCode(m,n,x,y) m个数字  显示大小为n   边宽x   边高y
 * 自己改写记录session $code
 */
session_start();
vCode(4, 15); //4个数字,显示大小为15

function vCode($num = 4, $size = 20, $width = 0, $height = 0) {
 !$width && $width = $num * $size * 4 / 5 + 5;
 !$height && $height = $size + 10;
 // 去掉了 0 1 O l 等
 $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";
 $code = '';
 for ($i = 0; $i < $num; $i++) {
  $code .= $str[mt_rand(0, strlen($str)-1)];
 }
 // 画图像
 $im = imagecreatetruecolor($width, $height);
 // 定义要用到的颜色
 $back_color = imagecolorallocate($im, 235, 236, 237);
 $boer_color = imagecolorallocate($im, 118, 151, 199);
 $text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
 // 画背景
 imagefilledrectangle($im, 0, 0, $width, $height, $back_color);
 // 画边框
 imagerectangle($im, 0, 0, $width-1, $height-1, $boer_color);
 // 画干扰线
 for($i = 0;$i < 5;$i++) {
  $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  imagearc($im, mt_rand(- $width, $width), mt_rand(- $height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color);
 }
 // 画干扰点
 for($i = 0;$i < 50;$i++) {
  $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);
 }
 // 画验证码
 @imagefttext($im, $size , 0, 5, $size + 3, $text_color, 'c:\WINDOWS\Fonts\simsun.ttc', $code);
 $_SESSION["VerifyCode"]=$code;
 header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
 header("Content-type: image/png;charset=gb2312");
 imagepng($im);
 imagedestroy($im);
}

?>

例2

使用PHP,结合session和GD库扩展开发的一个生成验证码的例子(w3c推荐),可以很方便的用于项目中。而且样式美观//首先开启session
session_start();
//定义前台显示验证码长&宽
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';
 
//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
//定义要生成验证码的字符串
$code = '';
 
$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}
 
$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);
 
/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);
 
$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
        $arr_text_color['green'], $arr_text_color['blue']);
 
$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
        $arr_noice_color['green'], $arr_noice_color['blue']);
 
/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
 
/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}
 
/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);
 
/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
//设置session,做验证
$_SESSION['6_letters_code'] = $code;
 
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);
 
  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}

个人推荐推荐第二个生成验证码程序代码,各位同学可尝试参考对比哦,最后一个是W3C标准生成的也是利用了php gd库。

缩略图如果是图片我们直接使用php gD库就可实现了,本文章要介绍的是Imagick把pdf生成png缩略图方法,这里我们要利用一个插件了,下面我来给大家演示一个实例。

php_imagick什么

一个可以供PHP调用ImageMagick功能的PHP扩展。使用这个扩展可以使PHP具备和ImageMagick相同的功能。
ImageMagick是一套功能强大、稳定而且免费的工具集和开发包,可以用来读、写和处理超过185种基本格式的图片文件,包括流行的TIFF, JPEG, GIF, PNG, PDF以及PhotoCD等格式。利用ImageMagick,你可以根据web应用程序的需要动态生成图片, 还可以对一个(或一组)图片进行改变大小、旋转、锐化、减色或增加特效等操作,并将操作的结果以相同格式或其它格式保存。

php_imagick怎么用

.创建一个缩略图并显示出来

 代码如下 复制代码

<?php

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

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,// aspect ratio is maintained

$image->thumbnailImage(100, 0);

echo $image;

?>

缩略GIF动画图片

 代码如下 复制代码

<?php

/* Create a new imagick object and read in GIF */

$im = new Imagick("example.gif");

/* Resize all frames */

foreach ($im as $frame) {

/* 50x50 frames */

$frame->thumbnailImage(50, 50);

/* Set the virtual canvas to correct size */

$frame->setImagePage(50, 50, 0, 0);

}/* Notice writeImages instead of writeImage */

$im->writeImages("example_small.gif", true);

?>

好了扯远了,我们来进入正题吧。


pdf生成png首页缩略图 (服务器需要支持Imagick)

 代码如下 复制代码

/**
* PDF2PNG  
* @param $pdf  待处理的PDF文件
* @param $path 待保存的图片路径
* @param $page 待导出的页面 -1为全部 0为第一页 1为第二页
* @return      保存好的图片路径和文件名
*/
 function pdf2png($pdf,$path,$page=0)
{  
   if(!is_dir($path))
   {
       mkdir($path,true);
   }
   if(!extension_loaded('imagick'))
   {  
     echo '没有找到imagick!' ;
     return false;
   }  
   if(!file_exists($pdf))
   {  
      echo '没有找到pdf' ;
       return false;  
   }  
   $im = new Imagick();  
   $im->setResolution(120,120);   //设置图像分辨率
   $im->setCompressionQuality(80); //压缩比

   $im->readImage($pdf."[".$page."]"); //设置读取pdf的第一页
   //$im->thumbnailImage(200, 100, true); // 改变图像的大小
   $im->scaleImage(200,100,true); //缩放大小图像
   $filename = $path."/". time().'.png';

   if($im->writeImage($filename) == true)
   {  
      $Return  = $filename;  
   }  
   return $Return;  
}  

$s=pdf2png('file/1371273225-ceshi_ppt.pdf','images');
echo "<div align=center><img src="".$s.""></div>";

图像添加水印在php中有很多种办法可以实现,他这些功能都是基于php中的GD库的,如果没有开户GD库是不可以使用水印功能的。

imagecopymerge() 函数用于拷贝并合并图像的一部分,成功返回 TRUE ,否则返回 FALSE 。

Windows下开启PHP的GD库支持

找到php.ini,打开内容,找到:

;extension=php_gd2.dll

把最前面的分号“;”去掉,再保存即可,如果本来就没有分号,那就是已经开启了

基本的语法

bool imagecopymerge( resource dst_im, resource src_im, int dst_x,
int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

参数说明: 参数 说明

dst_im 目标图像
src_im 被拷贝的源图像
dst_x 目标图像开始 x 坐标
dst_y 目标图像开始 y 坐标,x,y同为 0 则从左上角开始
src_x 拷贝图像开始 x 坐标
src_y 拷贝图像开始 y 坐标,x,y同为 0 则从左上角开始拷贝
src_w (从 src_x 开始)拷贝的宽度
src_h (从 src_y 开始)拷贝的高度
pct 图像合并程度,取值 0-100 ,当 pct=0 时,实际上什么也没做,反之完全合并。

当为 pct = 100 时对于调色板图像本函数和 imagecopy() 完全一样

知道了用法,要实现我们的功能就简单了,用下面的代码就可以轻松实现

 代码如下 复制代码

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

//原始图像
$dst = "images/flower_1.jpg";

//得到原始图片信息
$dst_im = imagecreatefromjpeg($dst);
$dst_info = getimagesize($dst);

//水印图像
$src = "images/logo.gif";
$src_im = imagecreatefromgif($src);
$src_info = getimagesize($src);

//水印透明度
$alpha = 30;

//合并水印图片
imagecopymerge($dst_im,$src_im,$dst_info[0]-$src_info[0],$dst_info[1]-$src_info[1],0,0,$src_info[0],
$src_info[1],$alpha);

//输出合并后水印图片
imagejpeg($dst_im);
imagedestroy($dst_im);
imagedestroy($src_im);
?>

新版本之后imagecopymerge函数几乎不使用了,我们可直接使用imagecopy来生成水印两个函数的功能是完全一样的。

//增加水印
$watermark   =1;
$watertype   =2;
$waterstring =''; 
$waterimg="z.png";    //水印图片
$sFilePath ='aa.jpg';
if($watermark==1)
{
 $image_size = getimagesize($sFilePath); //上传的图片
 $water_size = getimagesize($waterimg);  //水印图片
 $iinfo=getimagesize($sFilePath,$iinfo);
 $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
 $white=imagecolorallocate($nimage,255,255,255);
 $black=imagecolorallocate($nimage,0,0,0);
 $red=imagecolorallocate($nimage,255,0,0);
 imagefill($nimage,0,0,$white);
 switch ($iinfo[2])
 {
  case 1:
   $simage =imagecreatefromgif($sFilePath);
   break;
  case 2:
   $simage =imagecreatefromjpeg($sFilePath);
   break;
  case 3:
   $simage =imagecreatefrompng($sFilePath);
   break;
//            case 6:
//            $simage =imagecreatefromwbmp($sFilePath);
//            break;
  default:
   die("不支持的文件类型");
   exit;
 }
 
 imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
 
 switch($watertype)
 {
  case 1:   //加水印字符串
   imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
   break;
  case 2:   //加水印图片
   $simage1 =imagecreatefrompng($waterimg);     
   $x= $image_size[0]-$water_size[0];
   $y= $image_size[1]-$water_size[1];
   imagecopy($nimage,$simage1,$x,$y,0,0,240,65);
   imagedestroy($simage1);
   break;
 }
    
 switch ($iinfo[2])
 {
  case 1:
   imagegif($nimage, $sFilePath);
//            imagejpeg($nimage, $sFilePath);
   break;
  case 2:
   imagejpeg($nimage, $sFilePath);
   break;
  case 3:
   imagepng($nimage, $sFilePath);
   break;
//            case 6:
//            imagewbmp($nimage, $sFilePath);
//            //imagejpeg($nimage, $sFilePath);
//            break;
 }
 
 //覆盖原上传文件
 imagedestroy($nimage);
 imagedestroy($simage);
}

一个更好的功能,可以生成缩略并且还可以给图片添加水印


/***
 想操作图片
 先得把图片的大小,类型信息得到
 
 水印:就是把指定的水印复制到目标上,并加透明效果
 
 缩略图:就是把大图片复制到小尺寸画面上
 ***/  
 

 代码如下 复制代码

class ImageTool { 
    // imageInfo 分析图片的信息 
    // return array() 
    public static function imageInfo($image) { 
        // 判断图片是否存在 
        if (!file_exists($image)) { 
            return false; 
        } 
 
        $info = getimagesize($image); 
 
        if ($info == false) { 
            return false; 
        } 
 
        // 此时info分析出来,是一个数组 
        $img['width'] = $info[0]; 
        $img['height'] = $info[1]; 
        $img['ext'] = substr($info['mime'], strpos($info['mime'], '/') + 1); 
 
        return $img; 
    } 
 
    /*
     加水印功能
     parm String $dst 等操作图片
     parm String $water 水印小图
     parm String $save,不填则默认替换原始图
     */ 
    public static function water($dst, $water, $save = NULL, $pos = 2, $alpha = 50) { 
        // 先保证2个图片存在 
        if (!file_exists($dst) || !file_exists($water)) { 
            return false; 
        } 
 
        // 首先保证水印不能比待操作图片还大 
        $dinfo = self::imageInfo($dst); 
        $winfo = self::imageInfo($water); 
 
        if ($winfo['height'] > $dinfo['height'] || $winfo['width'] > $dinfo['width']) { 
            return false; 
        } 
 
        // 两张图,读到画布上! 但是图片可能是png,可能是jpeg,用什么函数读? 
        $dfunc = 'imagecreatefrom' . $dinfo['ext']; 
        $wfunc = 'imagecreatefrom' . $winfo['ext']; 
 
        if (!function_exists($dfunc) || !function_exists($wfunc)) { 
            return false; 
        } 
 
        // 动态加载函数来创建画布 
        $dim = $dfunc($dst); 
        // 创建待操作的画布 
        $wim = $wfunc($water); 
        // 创建水印画布 
 
        // 根据水印的位置 计算粘贴的坐标 
        switch($pos) { 
            case 0 : 
                // 左上角 
                $posx = 0; 
                $posy = 0; 
                break; 
 
            case 1 : 
                // 右上角 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = 0; 
                break; 
 
            case 3 : 
                // 左下角 
                $posx = 0; 
                $posy = $dinfo['height'] - $winfo['height']; 
                break; 
 
            default : 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = $dinfo['height'] - $winfo['height']; 
        } 
 
        // 加水印 
        imagecopymerge($dim, $wim, $posx, $posy, 0, 0, $winfo['width'], $winfo['height'], $alpha); 
 
        // 保存 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
            // 删除原图 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($dim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($wim); 
 
        return true; 
    } 
 
    /**
     thumb 生成缩略图
     等比例缩放,两边留白
     **/ 
    public static function thumb($dst, $save = NULL, $width = 200, $height = 200) { 
        // 首先判断待处理的图片存不存在 
        $dinfo = self::imageInfo($dst); 
        if ($dinfo == false) { 
            return false; 
        } 
 
        // 计算缩放比例 
        $calc = min($width / $dinfo['width'], $height / $dinfo['height']); 
 
        // 创建原始图的画布 
        $dfunc = 'imagecreatefrom' . $dinfo['ext']; 
        $dim = $dfunc($dst); 
 
        // 创建缩略画布 
        $tim = imagecreatetruecolor($width, $height); 
 
        // 创建白色填充缩略画布 
        $white = imagecolorallocate($tim, 255, 255, 255); 
 
        // 填充缩略画布 
        imagefill($tim, 0, 0, $white); 
 
        // 复制并缩略 
        $dwidth = (int)$dinfo['width'] * $calc; 
        $dheight = (int)$dinfo['height'] * $calc; 
 
        $paddingx = (int)($width - $dwidth) / 2; 
        $paddingy = (int)($height - $dheight) / 2; 
 
        imagecopyresampled($tim, $dim, $paddingx, $paddingy, 0, 0, $dwidth, $dheight, $dinfo['width'],

$dinfo['height']); 
 
        // 保存图片 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($tim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($tim); 
 
        return true; 
 
    } 
 

本文章来给大家介绍php生成雪花背景验证码程序代码 ,有需要的朋友可进入参考参考。

验证码生成程序

 代码如下 复制代码

<?php
session_start();
session_register("login_check_number");
//昨晚看到了chianren上的验证码效果,就考虑了一下,用PHP的GD库完成了类似功能
//先成生背景,再把生成的验证码放上去
$img_height=120;    //先定义图片的长、宽
$img_width=40;
if($HTTP_GET_VARS["act"]== "init"){
    //srand(microtime() * 100000);//PHP420后,srand不是必须的
    for($Tmpa=0;$Tmpa<4;$Tmpa++){
        $nmsg.=dechex(rand(0,15));
    }//by sports98


    $HTTP_SESSION_VARS[login_check_number] = $nmsg;

    //$HTTP_SESSION_VARS[login_check_number] = strval(mt_rand("1111","9999"));    //生成4位的随机数,放入session中
    //谁能做下补充,可以同时生成字母和数字啊??----由sports98完成了

    $aimg = imageCreate($img_height,$img_width);    //生成图片
    ImageColorAllocate($aimg, 255,255,255);            //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了
    $black = ImageColorAllocate($aimg, 0,0,0);        //定义需要的黑色
    ImageRectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//先成一黑色的矩形把图片包围

    //下面该生成雪花背景了,其实就是在图片上生成一些符号
    for ($i=1; $i<=100; $i++) {    //先用100个做测试
        imageString($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"*",imageColorAllocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
        //哈,看到了吧,其实也不是雪花,就是生成*号而已。为了使它们看起来"杂乱无章、5颜6色",就得在1个1个生成它们的时候,让它们的位置、颜色,甚至大小都用随机数,rand()或mt_rand都可以完成。
    }

    //上面生成了背景,现在就该把已经生成的随机数放上来了。道理和上面差不多,随机数1个1个地放,同时让他们的位置、大小、颜色都用成随机数~~
    //为了区别于背景,这里的颜色不超过200,上面的不小于200
    for ($i=0;$i<strlen($HTTP_SESSION_VARS[login_check_number]);$i++){
        imageString($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(1,10),mt_rand(1,$img_width/2), $HTTP_SESSION_VARS[login_check_number][$i],imageColorAllocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));
    }
    Header("Content-type: image/png");    //告诉浏览器,下面的数据是图片,而不要按文字显示
    ImagePng($aimg);                    //生成png格式。
    ImageDestroy($aimg);
}
?>

验证测试页面

 代码如下 复制代码

<?session_start();?>
<FORM METHOD=POST ACTION="">
<input type=text name=number maxlength=4><img src="YanZhengMa.php?act=init">
<INPUT TYPE="submit" name="sub">
</FORM>
<?
//检验校验码
if(isset($HTTP_POST_VARS["sub"])):
if($HTTP_POST_VARS["number"] != $HTTP_SESSION_VARS[login_check_number] || empty($HTTP_POST_VARS["number"])){
    echo "校验码不正确!" ;
}else{
    echo"验证码通过!";
}
endif;
show_source('test.php');
//以上本页的源码


//以下是生成验证码的源码
show_source('YanZhengMa.php');
?>

[!--infotagslink--]

相关文章

  • Windows批量搜索并复制/剪切文件的批处理程序实例

    这篇文章主要介绍了Windows批量搜索并复制/剪切文件的批处理程序实例,需要的朋友可以参考下...2020-06-30
  • BAT批处理判断服务是否正常运行的方法(批处理命令综合应用)

    批处理就是对某对象进行批量的处理,通常被认为是一种简化的脚本语言,它应用于DOS和Windows系统中。这篇文章主要介绍了BAT批处理判断服务是否正常运行(批处理命令综合应用),需要的朋友可以参考下...2020-06-30
  • PHP file_get_contents设置超时处理方法

    file_get_contents的超时处理话说,从PHP5开始,file_get_content已经支持context了(手册上写着:5.0.0 Added the context support. ),也就是说,从5.0开始,file_get_contents其实也可以POST数据。今天说的这篇是讲超时的,确实在...2013-10-04
  • C#多线程中的异常处理操作示例

    这篇文章主要介绍了C#多线程中的异常处理操作,涉及C#多线程及异常的捕获、处理等相关操作技巧,需要的朋友可以参考下...2020-06-25
  • postgresql 中的时间处理小技巧(推荐)

    这篇文章主要介绍了postgresql 中的时间处理小技巧(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-29
  • Python同时处理多个异常的方法

    这篇文章主要介绍了Python同时处理多个异常的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-29
  • C#异常处理中try和catch语句及finally语句的用法示例

    这篇文章主要介绍了C#异常处理中try和catch语句及finally语句的用法示例,finally语句的使用涉及到了C#的垃圾回收特性,需要的朋友可以参考下...2020-06-25
  • python 实现将Numpy数组保存为图像

    今天小编就为大家分享一篇python 实现将Numpy数组保存为图像,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • python用moviepy对视频进行简单的处理

    这篇文章主要介绍了python如何用moviepy对视频进行简单的处理,帮助大家更好的利用python处理视频,感兴趣的朋友可以了解下...2021-03-11
  • C#图像亮度调整的方法

    这篇文章主要介绍了C#图像亮度调整的方法,涉及C#操作图像亮度的相关技巧,需要的朋友可以参考下...2020-06-25
  • C#异常处理详解

    这篇文章介绍了C#异常处理,有需要的朋友可以参考一下...2020-06-25
  • C#图像透明度调整的方法

    这篇文章主要介绍了C#图像透明度调整的方法,涉及C#操作图像透明度的相关技巧,需要的朋友可以参考下...2020-06-25
  • sql server日志处理不当造成的隐患详解

    这篇文章主要给大家介绍了关于sql server日志处理不当造成的隐患的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用sql server具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-07-11
  • Spring MVC 处理一个请求的流程

    Spring MVC是Spring系列框架中使用频率最高的部分。不管是Spring Boot还是传统的Spring项目,只要是Web项目都会使用到Spring MVC部分。因此程序员一定要熟练掌握MVC部分。本篇博客简要分析Spring MVC处理一个请求的流程。...2021-02-06
  • go语言中的Carbon库时间处理技巧

    这篇文章主要介绍了go语言中的Carbon库时间处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-05
  • C++异常处理入门(try和catch)

    C++ 提供了异常机制,让我们能够捕获运行时错误,本文就详细的介绍了C++异常处理入门,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-08-09
  • Python-numpy实现灰度图像的分块和合并方式

    今天小编就为大家分享一篇Python-numpy实现灰度图像的分块和合并方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • python opencv实现图像配准与比较

    这篇文章主要为大家详细介绍了python opencv实现图像配准与比较,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 使用opencv识别图像红色区域,并输出红色区域中心点坐标

    这篇文章主要介绍了使用opencv识别图像红色区域,并输出红色区域中心点坐标,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-03
  • C#事务处理(Execute Transaction)实例解析

    这篇文章主要介绍了C#事务处理(Execute Transaction)实例解析,对于理解和学习事务处理有一定的帮助,需要的朋友可以参考下...2020-06-25