PHP图像图形处理入门教程(1/3)

 更新时间:2016年11月25日 16:58  点击:1525
这款php图片生成教程是一款从生成一个简单的图像到生成复杂的图形的php教程,下面就来看简单到复杂有12个生成图像实例。

1 生成一个简单图像。
2 设定图像的颜色。
3 在图像上绘制直线。
4 在图像上显示文字。
5 在图像中显示中文字符。
6 打开已存在的图片。
7 获取图片的相关属性。
8 函数getimagesize()的用法。
9 为上传图片添加水印效果。
10 生成已有图片的缩略图。
11 使用函数imagecopyresampled()。
12 生成带有底纹的数字验证码图片的php程序。

*/

//1 生成一个简单图像。

 代码如下 复制代码

$width = 200;
$height =200;

$img =  imagecreatetruecolor($width,$height) or die("不支持gd图像处理");
imagepng($img);
imagedestroy($img);

//2 设定图像的颜色。

 代码如下 复制代码

$width = 200;
$height =200;

$img =  imagecreatetruecolor($width,$height) or die("不支持gd图像处理");

$bg_color = imagecolorallocate($img, 255, 0, 0);
imagefill($img, 0, 0, $bg_color);

imagepng($img);
imagedestroy($img);

//3 在图像上绘制直线。

 代码如下 复制代码

$width = 200;
$height =300;

$img =  imagecreatetruecolor($width,$height) or die("不支持gd图像处理");

$line_color = imagecolorallocate($img, 255, 255, 255);
imageline($img,0,40,200,40,$line_color);
imageline($img,0,260,200,260,$line_color);

imagepng($img);
imagedestroy($img);

//4 在图像上显示文字。

 代码如下 复制代码

$width = 200;
$height =300;

$img =  imagecreatetruecolor($width,$height) or die("不支持gd图像处理");
$line_color = imagecolorallocate($img, 255, 255, 255);

imageline($img, 0, 40, 200, 40, $line_color);
imageline($img, 0, 260, 200, 260, $line_color);
imagestring($img, 5, 0, 60, "it's time to learn php!", $line_color);

imagepng($img);
imagedestroy($img);

//5 在图像中显示中文字符。

 代码如下 复制代码

$width = 200;
$height =300;

$img =  imagecreatetruecolor($width,$height) or die("不支持gd图像处理");
$line_color = imagecolorallocate($img, 255, 255, 255);
$font_type ="c://windows//fonts//simli.ttf";    //获取truetype字体,采用隶书字体

//“西游记”3个字16进制字符
$cn_char1 = chr(0xe8).chr(0xa5).chr(0xbf);
$cn_char2 = chr(0xe6).chr(0xb8).chr(0xb8);
$cn_char3 = chr(0xe8).chr(0xae).chr(0xb0);

//“吴承恩著”4个字16进制字符
$cn_str = chr(0xe5).chr(0x90).chr(0xb4).chr(0xe6).chr(0x89).chr(0xbf).chr(0xe6).chr(0x81).chr(0xa9);
$cn_str .= " ".chr(0xe8).chr(0x91).chr(0x97);

imageline($img, 0, 40, 200, 40, $line_color);
imageline($img, 0, 260, 200, 260, $line_color);

//竖排显示“西游记”3字
imagettftext($img, 30, 0, 10, 80, $line_color, $font_type,$cn_char1);
imagettftext($img, 30, 0, 10, 120, $line_color, $font_type,$cn_char2);
imagettftext($img, 30, 0, 10, 160, $line_color, $font_type,$cn_char3);

//横排显示“吴承恩著”4字
imagettftext($img, 15, 0, 90, 254, $line_color, $font_type,$cn_str);

imagepng($img);
imagedestroy($img);

//6 打开已存在的图片。
$img=imagecreatefromjpeg("tower.jpg");

imagejpeg($img);
imagedestroy($img);

//7 获取图片的相关属性。
$img=imagecreatefromjpeg("tower.jpg");

$x = imagesx($img);
$y = imagesy($img);
echo "图片tower.jpg的宽为:<b>$x</b> pixels";
echo "<br/>";
echo "<br/>";
echo "图片tower.jpg的高为:<b>$y</b> pixels";

//8 函数getimagesize()的用法。
$img_info=getimagesize("tower.jpg");

for($i=0; $i<4; ++$i)
{
    echo $img_info[$i];
    echo "<br/>";
}

?>

这是一款简单实用的php验证码生成程序了,主要是利用了php gd库来生成图形验证码,并且保存到session中,生成的代码是利用rand随机生成的。

 代码如下 复制代码

session_start();
$im=imagecreatetruecolor(100,30);
//分配颜色
$bg=imagecolorallocate($im,0,0,0);
$textcolor=imagecolorallocate($im,255,255,255);
//在图片上划线
for($i=0;$i<3;$i++){

$te1 = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imageline($im,0,rand(0,15),100,rand(0,15),$te1);
}
//在图片上打印200个点
for($i=0;$i<200;$i++){

 imagesetpixel($im,rand()%100,rand()%30,$te1);
}
for($i=0;$i<4;$i++){
 //dechex()把十进制转换成十六进制
 $rand.= dechex(rand(1,15));
}
$_session[check_pic]=$rand;
imagestring($im,5,rand(3,70),rand(3,15),$rand,$textcolor);
header("content-type:image/jpeg");
imagejpeg($im);

/*
生成验证的作用是防止用户乱注册了,这是一等的验证程序
*/

这是一款利用php自带的功能把指定的大图生成我们指定大小的缩略图代码哦,使用方便简单,只要把设置下面四个参数就可以生成自己想的大小的缩略图哦。
 代码如下 复制代码

function bigtosmallimg($file,$path,$w=120,$h=90)
{
 $img=$path.$file;
 $imgarr=getimagesize($img);
 $sw=$imgarr[0];//原图宽
 $sh=$imgarr[1];//原图高
 $stype=$imgarr[2];
 //按比例缩放
 if($sw/$sh>$w/$h){
  $mw=$w;
  $mh=(int)$sh*($w/$sw);
 }
 else{
  $mw=(int)$sw*($h/$sh);
  $mh=$h;
 }

 switch($stype){//根据上传好的图形文件类型新建一个用来生成缩略图的源文件。
   case 1:
    $srcf = imagecreatefromgif($img);
    break;
   case 2:
    $srcf = imagecreatefromjpeg($img);
    break;
   case 3:
    $srcf = imagecreatefrompng($img);
    break;
   default:
    showmsg('程序调用错误。');
    break;
 }

 $desf =imagecreatetruecolor($mw,$mh);

 imagecopyresampled($desf,$srcf,0,0,0,0,$mw,$mh,$sw,$sh);
 $sm_name=$path."s_".$file;
 switch($stype){
  case 1:
   imagegif($desf,$sm_name);
   break;
  case 2:
   imagejpeg($desf,$sm_name);
   break;
  case 3:
   imagepng($desf,$sm_name);
   break;
  default:
   showmsg('无法生成www.111cn.net' . $stype . '的缩略图。');
   break;
 }
 imagedestroy($desf);
 imagedestroy($srcf);

}

//此缩略图调用方法

 代码如下 复制代码

bigtosmallimg($file,$path,$w=120,$h=90);
/*

$file = 图片的路径
$path = 生成后保存的路径
$w =图片宽度
$h =图片高度
*/

以前写的验证码程序都是提供了源代码,但是没真的实的图形验证码生成到验证实例,这次我们一个完整的php 验证实例产生了。

有3个文件:
authcode.php-----验证码的生成php文件
authcode.html-----前台显示页面
dealauthcode.php-----ajax提交到的后台处理判断验证码是否正确的处理页面
*/
?>

前台调用验证码代码

 代码如下 复制代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>验证码ajax验证</title>
<style type="text/css教程">
        *{ font-size:12px;}
        a{ text-decoration:none;}
        a:hover{ text-decoration:underline; color:red;}
</style>
<script language="网页特效" src="http://code.jquery.com/jquery-1.4.2.min.网页特效"></script>
<script language="网页特效">
        $(document).ready(function(){
                /*----------------看不清楚,换张图片-----------*/
                $("#chang_authcode_btn").click(function(){
                        var authcode_url = "authcode.php?t="+math.random(0,1);
                        $("#authcode_img").attr('src',authcode_url);
                });               
                /*----------------检测验证码-----------*/       
                $("#authcode").bind({
                        'focusin':function(){
                                /**
                                 *得到焦点
                                 *我将img图片移除,若只改变src为'
                                 *'的话,在ie下会呈现出一个无图片的小图片,
                                 *所以我这里选择直接把img元素移除
                                 */
                                $(this).next('label').children('img').remove();
                                $(this).next('label').children('span').text('');
                        },               
                        'focusout':function(){
                                /**
                                 *失去焦点
                                 *这里要做的事情主要有下列几个:
                                 *(1)先用网页特效验证用户输入的验证是不是4位合法的字符,正则匹配
                                 *(2)如果正则匹配失败(不是合法的4位字符),在更新次验证码图片(也就是再触发一次"看不清楚"的a标签的点击事件)
                                 */
                                 var input_authcode = $(this).val();
                                 var authcode_regex = new regexp('^[a-z0-9]{4}','i');
                                 if(!authcode_regex.test(input_authcode)){//不是合法的4位字符串,显示错误信息给用户
                                        $(this).next('label').prepend("<img src='input_error.gif'/>");//加上错误图标
                                        $(this).next('label').children('span').text('输入的验证码格式错误!');//加上错误提示信息
                                        $("#chang_authcode_btn").trigger('click');//再次刷新图片
                                 }else{//ajax服务器验证,就是把用户的输入的验证码提交到服务器上的某个验证页面来处理!
                                         $.get('dealauthcode.php',{authcode:input_authcode},function(check_result){
                                                if(check_result=='mis_match'){//服务器验证没通过
                                                        $("#authcode").next('label').prepend("<img src='input_error.gif'/>");//加上错误图标
                                                        $("#authcode").next('label').children('span').text('验证码输入错误!');//加上错误提示信息
                                                        $("#chang_authcode_btn").trigger('click');//再次刷新图片
                                                }else{//服务器验证通过了
                                                        $("#authcode").next('label').prepend("<img src='input_ok.gif'/>");//加上正确图标
                                                        $("#authcode").next('label').children('span').text('验证码输入正确!');//加上正确提示信息       
                                                }                                                                                
                                         });
                                 }
                        }
                });               
        });
</script>
</head>
<body>
<div >
        <div><img id="authcode_img" src="authcode.php" /> <a id="chang_authcode_btn" style="cursor:pointer">看不清楚?换一张!</a></div>
        <div>验证码:<input id="authcode" type="text" size="20" /><label><span class="error_msg"></span></label></div>
</div>
</body>
</html>

dealauthcode.php-----ajax提交到的后台处理判断验证码是否正确的处理页面

 代码如下 复制代码
<?php
        session_start();
       $authcode = $_get['authcode'];
//这里的$_session['authcode']是在验证码authcode页面产生的
if(strtoupper($authcode)!= $_session['authcode']){   
echo 'mis_match';       
        }
?>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<?php

class upfileclass {

 var $upfile, $upfile_name, $upfile_size;
 # $upfile 临时文件名 $_files['tmp_name'] ,$upfile_name 文件名 $_files['name'] ,$upfile_size 文件大小$_files['size'];

 var $new_upfile_name;   # 上传后的文件名称 ;
 var $fleth, $fileextent; # 文件扩展名(类型) ;
 var $f1, $f2, $f3;   # 文件保存路径(多级) upfiles/2008-01/08/;
 var $filename;    # 文件(带路径) ;
 var $filepath; #相对路径用来删除文件;
 var $maxsize, $file_type; # 允许上传文件的大小 允许上传文件的类型 ;

 var $buildfile,$newfile,$file_width,$file_height,$rate;

 function upfileclass($upfile,$upfile_name,$upfile_size){
   $this->upfile = $upfile;
   $this->upfile_name = $upfile_name;
   $this->upfile_size = $upfile_size;
   $this->new_upfile_name = $this->createnewfilename($this->upfile_name);
   $this->f1 = "upfiles";
   $this->f2 = $this->f1."/".date('y')."-".date('m');
   $this->f3 = $this->f2."/".date('d');
   $this->filename = $this->f3 . "/" . $this->new_upfile_name;
   $this->maxsize = 500*1024;    # 文件大小 500kb
   $this->file_type = "gif/jpg/jpeg/png/bmp"; # 允许上传的文件类型
 }

 # 创建新文件名 (原文件名)
 function createnewfilename($file_name){
    $this->fleth = explode(".",$file_name);
    $this->fileextent = $this->fleth[(int)count($this->fleth)-1]; # 获取文件后缀;
    $tmps教程tr = date('ymd').rand(0,time()) . "." .$this->fileextent;    # 创建新文件名;
    return $tmpstr;
 }

 # 检测文件类型是否正确
 function chk_fileextent(){
    $iwtrue = 0;
    $fle = explode("/",$this->file_type);
    for($i=0; $i < count($fle); $i++){
     if($this->fileextent == $fle[$i]){
     $iwtrue = (int) $iwtrue + 1;
     }
    }
    if( $iwtrue == 0 ){
  $this->msg("文件不符合 ".$this->file_type." 格式!");
    }
 }

 # 提示错误信息并终止操作
 function msg($error){
    echo "<script language="网页特效"> ";
    echo " alert('".$error."'); ";
    echo " window.history.back(); ";
    echo "</script> ";
    die();
 }

 # 保存文件
 function savefile(){
    $this->chk_fileextent();
    $this->chk_filesize();
    $this->createfolder( "../".$this->f1 );
    $this->createfolder( "../".$this->f2 );
    $this->createfolder( "../".$this->f3 );
    return $this->chk_savefile();
 }

 # 检测上传结果是否成功
 function chk_savefile(){
    $copymsg = copy($this->upfile,"../".$this->filename);
    if( $copymsg ){
   return $this->filename;
    }
    else{
   $this->msg("文件上传失败! 请重新上传! ");
    }
 }

 # 创建文件夹
 function createfolder($foldername){
    if( !is_dir($foldername) ){
   mkdir($foldername,0777);
    }
 }

 # 检测文件大小
 function chk_filesize(){
    if( $this->upfile_size > $this->maxsize ){
  $this->msg("目标文件不能大于". $this->maxsize/1024 ." kb");
    }
 }

 # 删除文件($filepath 文件相对路径)
 function deletefile($filepath){
    if( !is_file($filepath) ){
   return false;
    }
    else{
   $ending = @unlink($filepath);
   return $ending;
    }
 }

 /*
    函数:生成缩略图
  makebuild("/www.111cn.net/a.jpg","news/b.jpg","100");
    参数:
    echo $buildfile;   原图 带路径
    echo $newfile;    生成的缩略图 带路径
    echo $file_width;   缩略图宽度值
    echo $file_height;   缩略图高度值 (默认为宽度的比例值)
    echo $rate;     缩略图象品质;
 */
 function makebuild($buildfile,$newfile,$file_width,$file_height=0,$rate=100) {
    if(!is_file($buildfile)){
   $this->msg("文件 ".$buildfile." 不是一个有效的图形文件! 系统无法生成该文件的缩略图!");
   return false;
    }
    $data = getimagesize($buildfile);
    switch($data[2]){
  case 1:
   $im = @imagecreatefromgif($buildfile);
   break;
  case 2:
   $im = @imagecreatefromjpeg($buildfile);
   break;
  case 3:
   $im = @imagecreatefrompng($buildfile);
   break;
    }
    if(!$im){
   return false;
    }
    else{
   $srcw = imagesx($im);  # 取得原图宽度;
   $srch = imagesy($im); # 取得原图高度;
   $dstx = 0;
   $dsty = 0;
   
  if($file_height==0){
   $file_height = $file_width/$srcw*$srch;
  }
   
  if ($srcw*$file_height>$srch*$file_width){
   $ffile_height = round($srch*$file_width/$srcw);
   $dsty = floor(($file_height-$ffile_height)/2);
   $ffile_width = $file_width;
  }
  else {
   $ffile_width = round($srcw*$file_height/$srch);
   $dstx = floor(($file_width-$ffile_width)/2);
   $ffile_height = $file_height;
  }
  $ni = imagecreatetruecolor($file_width,$file_height);
  $dstx = ($dstx<0)?0:$dstx;
  $dsty = ($dstx<0)?0:$dsty;
  $dstx = ($dstx>($file_width/2))?floor($file_width/2):$dstx;
  $dsty = ($dsty>($file_height/2))?floor($file_height/s):$dsty;
  imagecopyresized($ni,$im,$dstx,$dsty,0,0,$ffile_width,$ffile_height,$srcw,$srch);
   
  imagejpeg($ni,$newfile,$rate); # 生成缩略图;
  imagedestroy($im);     # imagedestroy(resource) 释放image关联的内存
    }
 }

}
?>

</body>
</html>

[!--infotagslink--]

相关文章

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

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

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

    这篇文章主要给大家介绍的是关于Lua语言新手入门的简单教程,文中通过示例代码一步步介绍的非常详细,对各位新手们的入门提供了一个很方便的教程,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧。...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
  • C#异常处理详解

    这篇文章介绍了C#异常处理,有需要的朋友可以参考一下...2020-06-25
  • CocosCreator入门教程之用TS制作第一个游戏

    这篇文章主要介绍了CocosCreator入门教程之用TS制作第一个游戏,对TypeScript感兴趣的同学,一定要看一下...2021-04-16
  • Python-numpy实现灰度图像的分块和合并方式

    今天小编就为大家分享一篇Python-numpy实现灰度图像的分块和合并方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • sql server日志处理不当造成的隐患详解

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

    JS与HTML之间的交互通过事件实现。事件就是文档或浏览器窗口中发生的一些特定的交互瞬间。可以使用监听器(或处理程序)来预定事件,以便事件发生时执行相应的代码。本文将介绍JS事件相关的基础知识。...2017-04-03
  • Spring MVC 处理一个请求的流程

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

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