php 给图片加水印三

 更新时间:2016年11月25日 16:06  点击:1545

<?

function setMaskTxtPct($n)
    {
        $this->mask_txt_pct = (int)$n;
    }
 
    /**
     * 设置缩略图边框
     *
     * @param    (类型)     (参数名)    (描述)
     */
    function setDstImgBorder($size=1, $color="#000000")
    {
        $this->img_border_size  = (int)$size;
        $this->img_border_color = $color;
    }
 
    /**
     * 水平翻转
     */
    function flipH()
    {
        $this->_flip_x++;
    }
 
    /**
     * 垂直翻转
     */
    function flipV()
    {
        $this->_flip_y++;
    }
 
    /**
     * 设置剪切类型
     *
     * @param    (类型)     (参数名)    (描述)
     */
    function setCutType($type)
    {
        $this->cut_type = (int)$type;
    }
 
    /**
     * 设置图片剪切
     *
     * @param    integer     $width    矩形剪切
     */
    function setRectangleCut($width, $height)
    {
        $this->fill_w = (int)$width;
        $this->fill_h = (int)$height;
    }
 
    /**
     * 设置源图剪切起始坐标点
     *
     * @param    (类型)     (参数名)    (描述)
     */
    function setSrcCutPosition($x, $y)
    {
        $this->src_x  = (int)$x;
        $this->src_y  = (int)$y;
    }
 
    /**
     * 创建图片,主函数
     * @param    integer    $a     当缺少第二个参数时,此参数将用作百分比,
     *                             否则作为宽度值
     * @param    integer    $b     图片缩放后的高度
     */
    function createImg($a, $b=null)
    {
        $num = func_num_args();
        if(1 == $num)
        {
            $r = (int)$a;
            if($r < 1)
            {
                die("图片缩放比例不得小于1");
            }
            $this->img_scale = $r;
            $this->_setNewImgSize($r);
        }
 
        if(2 == $num)
        {
            $w = (int)$a;
            $h = (int)$b;
            if(0 == $w)
            {
                die("目标宽度不能为0");
            }
            if(0 == $h)
            {
                die("目标高度不能为0");
            }
            $this->_setNewImgSize($w, $h);
        }
 
        if($this->_flip_x%2!=0)
        {
            $this->_flipH($this->h_src);
        }
 
        if($this->_flip_y%2!=0)
        {
            $this->_flipV($this->h_src);
        }
        $this->_createMask();
        $this->_output();
 
        // 释放
        if(imagedestroy($this->h_src) && imagedestroy($this->h_dst))
        {
            Return true;
        }
        else
        {
            Return false;
        }
    }
 
   ?>

<?

 /**
     * 生成水印,调用了生成水印文字和水印图片两个方法
     */
    function _createMask()
    {
        if($this->mask_word)
        {
            // 获取字体信息
            $this->_setFontInfo();
 
            if($this->_isFull())
            {
                die("水印文字过大");
            }
            else
            {
                $this->h_dst = imagecreatetruecolor($this->dst_w, $this->dst_h);
                $white = ImageColorAllocate($this->h_dst,255,255,255);
                imagefilledrectangle($this->h_dst,0,0,$this->dst_w,$this->dst_h,$white);// 填充背景色
                $this->_drawBorder();
                imagecopyresampled( $this->h_dst, $this->h_src,
                                    $this->start_x, $this->start_y,
                                    $this->src_x, $this->src_y,
                                    $this->fill_w, $this->fill_h,
                                    $this->copy_w, $this->copy_h);
                $this->_createMaskWord($this->h_dst);
            }
        }
 
        if($this->mask_img)
        {
            $this->_loadMaskImg();//加载时,取得宽高
 
            if($this->_isFull())
            {
                // 将水印生成在原图上再拷
                $this->_createMaskImg($this->h_src);
                $this->h_dst = imagecreatetruecolor($this->dst_w, $this->dst_h);
                $white = ImageColorAllocate($this->h_dst,255,255,255);
                imagefilledrectangle($this->h_dst,0,0,$this->dst_w,$this->dst_h,$white);// 填充背景色
                $this->_drawBorder();
                imagecopyresampled( $this->h_dst, $this->h_src,
                                    $this->start_x, $this->start_y,
                                    $this->src_x, $this->src_y,
                                    $this->fill_w, $this->fill_h,
                                    $this->copy_w, $this->copy_h);
            }
            else
            {
                // 创建新图并拷贝
                $this->h_dst = imagecreatetruecolor($this->dst_w, $this->dst_h);
                $white = ImageColorAllocate($this->h_dst,255,255,255);
                imagefilledrectangle($this->h_dst,0,0,$this->dst_w,$this->dst_h,$white);// 填充背景色
                $this->_drawBorder();
                imagecopyresampled( $this->h_dst, $this->h_src,
                                    $this->start_x, $this->start_y,
                                    $this->src_x, $this->src_y,
                                    $this->fill_w, $this->fill_h,
                                    $this->copy_w, $this->copy_h);
                $this->_createMaskImg($this->h_dst);
            }
        }
 
        if(empty($this->mask_word) && empty($this->mask_img))
        {
            $this->h_dst = imagecreatetruecolor($this->dst_w, $this->dst_h);
            $white = ImageColorAllocate($this->h_dst,255,255,255);
            imagefilledrectangle($this->h_dst,0,0,$this->dst_w,$this->dst_h,$white);// 填充背景色
            $this->_drawBorder();
 
            imagecopyresampled( $this->h_dst, $this->h_src,
                        $this->start_x, $this->start_y,
                        $this->src_x, $this->src_y,
                        $this->fill_w, $this->fill_h,
                        $this->copy_w, $this->copy_h);
        }
    }
 
    /**
     * 画边框
     */
    function _drawBorder()
    {
        if(!empty($this->img_border_size))
        {
            $c = $this->_parseColor($this->img_border_color);
            $color = ImageColorAllocate($this->h_src,$c[0], $c[1], $c[2]);
            imagefilledrectangle($this->h_dst,0,0,$this->dst_w,$this->dst_h,$color);// 填充背景色
        }
    }
 
    /**
     * 生成水印文字
     */
    function _createMaskWord($src)
    {
        $this->_countMaskPos();
        $this->_checkMaskValid();
 
        $c = $this->_parseColor($this->mask_font_color);
        $color = imagecolorallocatealpha($src, $c[0], $c[1], $c[2], $this->mask_txt_pct);
 
        if(is_numeric($this->font))
        {
            imagestring($src,
                        $this->font,
                        $this->mask_pos_x, $this->mask_pos_y,
                        $this->mask_word,
                        $color);
        }
        else
        {
            imagettftext($src,
                        $this->font_size, 0,
                        $this->mask_pos_x, $this->mask_pos_y,
                        $color,
                        $this->font,
                        $this->mask_word);
        }
    }
 
    /**
     * 生成水印图
     */
    function _createMaskImg($src)
    {
        $this->_countMaskPos();
        $this->_checkMaskValid();
        imagecopymerge($src,
                        $this->h_mask,
                        $this->mask_pos_x ,$this->mask_pos_y,
                        0, 0,
                        $this->mask_w, $this->mask_h,
                        $this->mask_img_pct);
 
        imagedestroy($this->h_mask);
    }
 
    /**
     * 加载水印图
     */
    function _loadMaskImg()
    {
        $mask_type = $this->_getImgType($this->mask_img);
        $this->_checkValid($mask_type);
 
        // file_get_contents函数要求php版本>4.3.0
        $src = '';
        if(function_exists("file_get_contents"))
        {
            $src = file_get_contents($this->mask_img);
        }
        else
        {
            $handle = fopen ($this->mask_img, "r");
            while (!feof ($handle))
            {
                $src .= fgets($fd, 4096);
            }
            fclose ($handle);
        }
        if(empty($this->mask_img))
        {
            die("水印图片为空");
        }
        $this->h_mask = ImageCreateFromString($src);
        $this->mask_w = $this->getImgWidth($this->h_mask);
        $this->mask_h = $this->getImgHeight($this->h_mask);
    }
 
    /**
     * 图片输出
     */
    function _output()
    {
        $img_type  = $this->img_type;
        $func_name = $this->all_type[$img_type]['output'];
        if(function_exists($func_name))
        {
            // 判断浏览器,若是IE就不发送头
            if(isset($_SERVER['HTTP_USER_AGENT']))
            {
                $ua = strtoupper($_SERVER['HTTP_USER_AGENT']);
                if(!preg_match('/^.*MSIE.*\)$/i',$ua))
                {
                    header("Content-type:$img_type");
                }
            }
            $func_name($this->h_dst, $this->dst_img, $this->img_display_quality);
        }
        else
        {
            Return false;
        }
    }
 
    /**
     * 分析颜色
     *
     * @param    string     $color    十六进制颜色
     */
    function _parseColor($color)
    {
        $arr = array();
        for($ii=1; $ii<strlen ($color); $ii++)
        {
            $arr[] = hexdec(substr($color,$ii,2));
            $ii++;
        }
 
        Return $arr;
    }
 
    /**
     * 计算出位置坐标
     */
   ?>

<?

 /**
     * 设置水印字体
     *
     * @param    string|integer    $font    字体
     */
    function setMaskFont($font=2)
    {
        if(!is_numeric($font) && !file_exists($font))
        {
            die("字体文件不存在");
        }
        $this->font = $font;
    }
 
    /**
     * 设置文字字体大小,仅对truetype字体有效
     */
    function setMaskFontSize($size = "12")
    {
        $this->font_size = $size;
    }
 
    /**
     * 设置图片水印
     *
     * @param    string    $img     水印图片源
     */
    function setMaskImg($img)
    {
        $this->mask_img = $img;
    }
 
    /**
     * 设置水印横向偏移
     *
     * @param    integer     $x    横向偏移量
     */
    function setMaskOffsetX($x)
    {
        $this->mask_offset_x = (int)$x;
    }
 
    /**
     * 设置水印纵向偏移
     *
     * @param    integer     $y    纵向偏移量
     */
    function setMaskOffsetY($y)
    {
        $this->mask_offset_y = (int)$y;
    }
 
    /**
     * 指定水印位置
     *
     * @param    integer     $position    位置,1:左上,2:左下,3:右上,0/4:右下
     */
    function setMaskPosition($position=0)
    {
        $this->mask_position = (int)$position;
    }
 
    /**
     * 设置图片合并程度
     *
     * @param    integer     $n    合并程度
     */
    function setMaskImgPct($n)
    {
        $this->mask_img_pct = (int)$n;
    }
 
    /**
     * 设置文字合并程度
     *
     * @param    integer     $n    合并程度
     */
    ?>

/*
作者: 牛哄哄
Q Q: 455703030
*/
function template($template,$cacheFile,$set)
{
is_readable($template) || exit('模板文件不存在!');
filemtime($template) > @filemtime($cacheFile) && parse_template($template,$cacheFile);
$inTemplate = true;
is_readable($cacheFile) ? include $cacheFile : exit('无法读取缓存,缓存路径可能有误!');
}
function parse_template($template,$cacheFile='')
{
$content = file_get_contents($template);
$content = preg_replace('/\{\*([^\{\}]*)\*\}/','',$content);
$content = preg_replace('/\$([A-Za-z0-9_]+)/','$set[\'\\1\']',$content);
$content = preg_replace('/\$\[([A-Za-z0-9_]+)\]/','$\\1',$content);
$content = preg_replace('/\{\$([A-Za-z0-9_\[\]\'"]+)\}/','<? echo $\\1; ?>',$content);
$content = preg_replace('/\{include\(([^\{\}]+)\)\}/','<? include \\1; ?>',$content);
$content = preg_replace('/\{echofile\(([^\{\}]+)\)\}/','<? echo file_get_contents(\\1); ?>',$content);
$content = preg_replace('/\{code\(([^\{\}]+)\)\}/','<? \\1; ?>',$content);
$content = preg_replace('/\{if\(([^\{\}]+)\)\}/','<? if (\\1) { ?>',$content);
$content = preg_replace('/\{elseif\(([^\{\}]+)\)\}/','<? } elseif(\\1) { ?>',$content);
$content = preg_replace('/\{while\(([^\{\}]+)\)\}/','<? while (\\1) { ?>',$content);
$content = preg_replace('/\{foreach\(([^\{\}]+)\)\}/','<? foreach (\\1) { ?>',$content);
$content = str_replace(array('{else}','{/if}','{/while}','{/foreach}'),array('<? }else{ ?>','<? } ?>','<? } ?>','<? } ?>'),$content);
if (preg_match_all('/\{template\(([^\{\}]+)\)\}/',$content,$tplName))
{
  foreach ($tplName[1] as $value) $tplContent[] = parse_template(eval('return '.$value.';'));
  $content = str_replace($tplName[0],$tplContent,$content);
}
if ('' == $cacheFile) return $content;
@file_put_contents($cacheFile,'<? true===$inTemplate || exit(\'非法访问!\'); ?>'.$content);
}

1,修复一个因为疏忽造成的小BUG,编译之后的代码少 了一个{符号,呵呵
2,更改模板嵌套的编译模式,现在这种模式使用更简单方便,也更符合大家的习惯

3,增加了一个新的功能,其实本来提供的功能,也可以实现此功能,但是毕竟不专业,用起来不方便。此功能用来直接输出一个静态的文件,我曾经做过测试,这样直接输出,效率要比include高的多的多

此模板函数提供的标签及功能:
1,添加注释
{*   *}
2,输出变量
{$i}   //需要对变量进行格式化,可以使用{code()}标签来执行一个函数进行格式化输出
3,包含一个动态文件
{include()}
4,包含一个静态文件
{echofile()}
5,嵌套一个模板
{template()}
6,判断,分支
{if()} {elseif()}  {else} {/if}
7,循环
{while()}   {/while}
{foreach()}  {/foreach}
8,执行一段PHP代码,包括赋值,函数等等等等
{code()}
有了这些东西,基本上就没有什么工作完成不了了。
内附比较详细的使用说明


 
参数说明:
$max_file_size  : 上传文件大小限制, 单位BYTE
$destination_folder : 上传文件路径
$watermark   : 是否附加水印(1为加水印,其他为不加水印);
使用说明:
1. 将PHP.INI文件里面的"extension=php_gd2.dll"一行前面的;号去掉,因为我们要用到GD库;
2. 将extension_dir =改为你的php_gd2.dll所在目录;
****************************************************/
//上传文件类型列表
$uptypes=array(
    'image/jpg', 
    'image/jpeg',
    'image/png',
    'image/pjpeg',
    'image/gif',
    'image/bmp',
    'image/x-png'
);
$max_file_size=2000000;     //上传文件大小限制, 单位BYTE
$destination_folder="uploadimg/"; //上传文件路径
$watermark=1;      //是否附加水印(1为加水印,其他为不加水印);
$watertype=1;      //水印类型(1为文字,2为图片)
$waterposition=1;     //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);
$waterstring="http://www.xplore.cn/";  //水印字符串
$waterimg="xplore.gif";    //水印图片
$imgpreview=1;      //是否生成预览图(1为生成,其他为不生成);
$imgpreviewsize=1/2;    //缩略图比例
?>
<html>
<head>
<title>ZwelL图片上传程序</title>
<style type="text/css">
<!--
body
{
     font-size: 9pt;
}
input
{
     background-color: #66CCFF;
     border: 1px inset #CCCCCC;
}
-->
</style>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="upform">
  上传文件:
  <input name="upfile" type="file">
  <input type="submit" value="上传"><br>
  允许上传的文件类型为:<?=implode(', ',$uptypes)?>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
    //是否存在文件
    {
         echo "图片不存在!";
         exit;
    }
    $file = $_FILES["upfile"];
    if($max_file_size < $file["size"])
    //检查文件大小
    {
        echo "文件太大!";
        exit;
    }
    if(!in_array($file["type"], $uptypes))
    //检查文件类型
    {
        echo "文件类型不符!".$file["type"];
        exit;
    }
    if(!file_exists($destination_folder))
    {
        mkdir($destination_folder);
    }
    $filename=$file["tmp_name"];
    $image_size = getimagesize($filename);
    $pinfo=pathinfo($file["name"]);
    $ftype=$pinfo['extension'];
    $destination = $destination_folder.time().".".$ftype;
    if (file_exists($destination) && $overwrite != true)
    {
        echo "同名文件已经存在了";
        exit;
    }
    if(!move_uploaded_file ($filename, $destination))
    {
        echo "移动文件出错";
        exit;
    }
    $pinfo=pathinfo($destination);
    $fname=$pinfo[basename];
    echo " <font color=red>已经成功上传</font><br>文件名:  <font color=blue>".$destination_folder.$fname."</font><br>";
    echo " 宽度:".$image_size[0];
    echo " 长度:".$image_size[1];
    echo "<br> 大小:".$file["size"]." bytes";
    if($watermark==1)
    {
        $iinfo=getimagesize($destination,$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($destination);
            break;
            case 2:
            $simage =imagecreatefromjpeg($destination);
            break;
            case 3:
            $simage =imagecreatefrompng($destination);
            break;
            case 6:
            $simage =imagecreatefromwbmp($destination);
            break;
            default:
            die("不支持的文件类型");
            exit;
        }
        imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
        imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);
        switch($watertype)
        {
            case 1:   //加水印字符串
            imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
            break;
            case 2:   //加水印图片
            $simage1 =imagecreatefromgif("xplore.gif");
            imagecopy($nimage,$simage1,0,0,0,0,85,15);
            imagedestroy($simage1);
            break;
        }
        switch ($iinfo[2])
        {
            case 1:
            //imagegif($nimage, $destination);
            imagejpeg($nimage, $destination);
            break;
            case 2:
            imagejpeg($nimage, $destination);
            break;
            case 3:
            imagepng($nimage, $destination);
            break;
            case 6:
            imagewbmp($nimage, $destination);
            //imagejpeg($nimage, $destination);
            break;
        }
        //覆盖原上传文件
        imagedestroy($nimage);
        imagedestroy($simage);
    }
    if($imgpreview==1)
    {
    echo "<br>图片预览:<br>";
    echo "<img src="".$destination."" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);
    echo " alt="图片预览:r文件名:".$destination."r上传时间:">";
    }
}
?>
</body>
</html>
 
这段代码是我在实现应用中经常用到地,拿出来希望给各位一小点点帮助.
[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Photoshop古装美女图片转为工笔画效果制作教程

    今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮

    jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮...2013-10-13
  • 利用JS实现点击按钮后图片自动切换的简单方法

    下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
  • js实现上传图片及时预览

    这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
  • Photoshop枪战电影海报图片制作教程

    Photoshop的这一款软件小编相信很多的人都已经是使用过了吧,那么今天小编在这里就给大家带来了用Photoshop软件制作枪战电影海报的教程,想知道制作步骤的玩家们,那么下面...2016-09-14
  • python opencv通过4坐标剪裁图片

    图片剪裁是常用的方法,那么如何通过4坐标剪裁图片,本文就详细的来介绍一下,感兴趣的小伙伴们可以参考一下...2021-06-04
  • 使用PHP下载CSS文件中的图片的代码

    共享一段使用PHP下载CSS文件中的图片的代码 复制代码 代码如下: <?php //note 设置PHP超时时间 set_time_limit(0); //note 取得样式文件内容 $styleFileContent = file_get_contents('images/style.css'); //not...2013-10-04
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • PHP swfupload图片上传的实例代码

    PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
  • C#中图片旋转和翻转(RotateFlipType)用法分析

    这篇文章主要介绍了C#中图片旋转和翻转(RotateFlipType)用法,实例分析了C#图片旋转及翻转Image.RotateFlip方法属性的常用设置技巧,需要的朋友可以参考下...2020-06-25
  • ps怎么制作图片阴影效果

    ps软件是现在很多人比较喜欢的,有着非常不错的使用效果,这次文章就给大家介绍下ps怎么制作图片阴影效果,还不知道制作方法的赶紧来看看。 ps图片阴影效果怎么做方法/...2017-07-06
  • OpenCV如何去除图片中的阴影的实现

    这篇文章主要介绍了OpenCV如何去除图片中的阴影的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-29
  • C#将图片和字节流互相转换并显示到页面上

    本文主要介绍用C#实现图片转换成字节流,字节流转换成图片,并根据图片路径返回图片的字节流,有需要的朋友可以参考下...2020-06-25
  • JavaScript 如何禁止用户保存图片

    这篇文章主要介绍了JavaScript 如何禁止用户保存图片,帮助大家完成需求,更好的理解和使用JavaScript,感兴趣的朋友可以了解下...2020-11-19
  • php上传图片学习笔记与心得

    我们在php中上传文件就必须使用#_FILE变量了,这个自动全局变量 $_FILES 从 PHP 4.1.0 版本开始被支持。在这之前,从 4.0.0 版本开始,PHP 支持 $HTTP_POST_FILES 数组。这...2016-11-25
  • JS实现图片的不间断连续滚动的简单实例

    下面小编就为大家带来一篇JS实现图片的不间断连续滚动的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-06-12