图像添加水印,php给图片加水印与上传图片加水印php类
分类:面向对象

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

最近在用Thinkphp的打水印的功能,发现只能打在左下角。 PHP打水印功还是很容易的,最要是用到

/*
* 功能:PHP图片水印 (水印支持图片或文字)
* 参数:
* $groundImage 背景图片,即需要加水印的图片,暂只支持GIF,JPG,PNG格式;
* $waterPos 水印位置,有10种状态,0为随机位置;
* 1为顶端居左,2为顶端居中,3为顶端居右;
* 4为中部居左,5为中部居中,6为中部居右;
* 7为底端居左,8为底端居中,9为底端居右;
* $waterImage 图片水印,即作为水印的图片,暂只支持GIF,JPG,PNG格式;
* $waterText 文字水印,即把文字作为为水印,支持ASCII码,不支持中文;
* $textFont 文字大小,值为1、2、3、4或5,默认为5;
* $textColor 文字颜色,值为十六进制颜色值,默认为#FF0000(红色);
*
* 注意:Support GD 2.0,Support FreeType、GIF Read、GIF Create、JPG 、PNG
* $waterImage 和 $waterText 最好不要同时使用,选其中之一即可,优先使用 $waterImage。
* 当$waterImage有效时,参数$waterString、$stringFont、$stringColor均不生效。
* 加水印后的图片的文件名和 $groundImage 一样。
* 作者:longware @ 2004-11-3 14:15:13
*/
function imageWaterMark($groundImage,$waterPos=0,$waterImage=”",$waterText=”",$textFont=5,$textColor=”#FF0000″)
{
$isWaterImage = FALSE;
$formatMsg = “暂不支持该文件格式,请用图片处理软件将图片转换为GIF、JPG、PNG格式。”;

wordpress默认情况下,裁剪的图片会直接裁剪图片的中间部分,例如你上传了一张美女图片,上传上去由于图片的尺寸超出了内部规定的尺寸,wordpress会对其进行裁剪,按照规定的尺寸裁剪好后生成另外一张图片进行保存,可惜的是,当你调用这张图片的时候发现,美女的头被卡擦了,这样的缩略图完全失去了吸引读者的功效,下面我们就来解决这个问题

 

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 )

//读取水印文件
if(!emptyempty($waterImage) && file_exists($waterImage))
{
$isWaterImage = TRUE;
$water_info = getimagesize($waterImage);
$water_w = $water_info[0];//取得水印图片的宽
$water_h = $water_info[1];//取得水印图片的高

复制代码代码如下:
/* Example Usage:
* bt_add_image_size( 'product-screenshot', 300, 300, array( 'left', 'top' ) );
* bt_add_image_size( 'product-feature', 460, 345, array( 'center', 'top' ) );
*/

 

将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度,其值范围从 0 到 100。当 pct = 0 时,实际上什么也没做,当为 100 时对于调色板图像本函数和 imagecopy() 完全一样,它对真彩色图像实现了 alpha 透明。

switch($water_info[2])//取得水印图片的格式
{
case 1:$water_im = imagecreatefromgif($waterImage);break;
case 2:$water_im = imagecreatefromjpeg($waterImage);break;
case 3:$water_im = imagecreatefrompng($waterImage);break;
default:die($formatMsg);
}
}

add_filter( 'intermediate_image_sizes_advanced', 'bt_intermediate_image_sizes_advanced' );
add_filter( 'wp_generate_attachment_metadata', 'bt_generate_attachment_metadata', 10, 2 );

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

图片 1

//读取背景图片
if(!emptyempty($groundImage) && file_exists($groundImage))
{
$ground_info = getimagesize($groundImage);
$ground_w = $ground_info[0];//取得背景图片的宽
$ground_h = $ground_info[1];//取得背景图片的高

/**
* Registers a new image size with cropping positions
*
* The $crop parameter works as in the 'add_image_size' function taking true or
* false values. If set to true, the default cropping position is 'center', 'center'.
*
* The $crop parameter also takes an array of the format
* array( x_crop_position, y_crop_position )
* x_crop_position can be 'left', 'center', 'right'
* y_crop_position can be 'top', 'center', 'bottom'
*
* @param string $name Image size identifier.
* @param int $width Image width.
* @param int $height Image height.
* @param bool|array $crop Optional, default is false. Whether to crop image to specified height and width or resize. An array can specify positioning of the crop area.
* @return bool|array False, if no image was created. Metadata array on success.
*/
function bt_add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
global $_wp_additional_image_sizes;
$_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => $crop );
}

Windows下开启PHP的GD库支持

我需要把水印打到图片的真中间,查看Thinkphp代码。发现,作者居然是写死了,,我只能做一个修改

switch($ground_info[2])//取得背景图片的格式
{
case 1:$ground_im = imagecreatefromgif($groundImage);break;
case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
case 3:$ground_im = imagecreatefrompng($groundImage);break;
default:die($formatMsg);
}
}
else
{
die(”需要加水印的图片不存在!”);
}

/**
* Returning no sizes (an empty array) will force
* wp_generate_attachment_metadata to skip creating intermediate image sizes on
* upload, then we can run our own resizing functions by hooking into the
* 'wp_generate_attachment_metadata' filter
*/
function bt_intermediate_image_sizes_advanced( $sizes ) {
return array();
}

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

/**
* 为图片添加水印
* @static public
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $postion 水印的具体位置 leftbottom rightbottom lefttop righttop center <新增>
* @param string $alpha 水印的透明度
* @return void
*/
static public function water($source, $water, $savename=null,$postion="center", $alpha=80) {
//检查文件是否存在
if (!file_exists($source) || !file_exists($water))
return false;
 
//图片信息
$sInfo = self::getImageInfo($source);
$wInfo = self::getImageInfo($water);
 
//如果图片小于水印图片,不生成图片
if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height']) return false; //建立图像 $sCreateFun = "imagecreatefrom" . $sInfo['type']; $sImage = $sCreateFun($source); $wCreateFun = "imagecreatefrom" . $wInfo['type']; $wImage = $wCreateFun($water); //设定图像的混色模式 imagealphablending($wImage, true); //图像位置,默认为右下角右对齐 $posArr = $this->WaterPostion($postion,$sInfo,$wInfo); //新增
 
   //生成混合图像
    imagecopymerge($sImage, $wImage, $posArr[0], $posArr[1], 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
 
   //输出图像
   $ImageFun = 'Image' . $sInfo['type'];
  //如果没有给出保存文件名,默认为原图像名
  if (!$savename) {
     $savename = $source;
     @unlink($source);
   }
 //保存图像
   $ImageFun($sImage, $savename);
      imagedestroy($sImage);
  }
 
  private function WaterPostion($postion,$sInfo,$wInfo)
  {
     $posY = $sInfo["height"] - $wInfo["height"];
     $posX = $sInfo["width"] - $wInfo["width"];
 
    switch($postion)
  {
     case "rightbottom":
        return array($posX,$posY);
     break;
 
     case "leftbottom":
        return array($wInfo["width"],$posY);
     break;
 
     case "lefttop":
       return array($wInfo["width"],$wInfo["height"]);
     break;
 
     case "righttop":
        return array($posX,$wInfo["height"]);
     break;
 
     case "center":
       return array($posX/2,$posY/2);
    break;
   }
}
好像就可以了~

//水印位置
if($isWaterImage)//图片水印
{
$w = $water_w;
$h = $water_h;
$label = “图片的”;
}
else//文字水印
{
$temp = imagettfbbox(ceil($textFont*5),0,”./cour.ttf”,$waterText);//取得使用 TrueType 字体的文本的范围
$w = $temp[2] - $temp[6];
$h = $temp[3] - $temp[7];
unset($temp);
$label = “文字区域”;
}
if( ($ground_w<$w) || ($ground_h<$h) )
{
echo “需要加水印的图片的长度或宽度比水印”.$label.”还小,无法生成水印!”;
return;
}
switch($waterPos)
{
case 0://随机
$posX = rand(0,($ground_w - $w));
$posY = rand(0,($ground_h - $h));
break;
case 1://1为顶端居左
$posX = 0;
$posY = 0;
break;
case 2://2为顶端居中
$posX = ($ground_w - $w) / 2;
$posY = 0;
break;
case 3://3为顶端居右
$posX = $ground_w - $w;
$posY = 0;
break;
case 4://4为中部居左
$posX = 0;
$posY = ($ground_h - $h) / 2;
break;
case 5://5为中部居中
$posX = ($ground_w - $w) / 2;
$posY = ($ground_h - $h) / 2;
break;
case 6://6为中部居右
$posX = $ground_w - $w;
$posY = ($ground_h - $h) / 2;
break;
case 7://7为底端居左
$posX = 0;
$posY = $ground_h - $h;
break;
case 8://8为底端居中
$posX = ($ground_w - $w) / 2;
$posY = $ground_h - $h;
break;
case 9://9为底端居右
$posX = $ground_w - $w;
$posY = $ground_h - $h;
break;
default://随机
$posX = rand(0,($ground_w - $w));
$posY = rand(0,($ground_h - $h));
break;
}

function bt_generate_attachment_metadata( $metadata, $attachment_id ) {
$attachment = get_post( $attachment_id );

;extension=php_gd2.dll

//设定图像的混色模式
imagealphablending($ground_im, true);

$uploadPath = wp_upload_dir();
$file = path_join($uploadPath['basedir'], $metadata['file']);

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

if($isWaterImage)//图片水印
{
imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件
}
else//文字水印
{
if( !emptyempty($textColor) && (strlen($textColor)==7) )
{
$R = hexdec(substr($textColor,1,2));
$G = hexdec(substr($textColor,3,2));
$B = hexdec(substr($textColor,5));
}
else
{
die(”水印文字颜色格式不正确!”);
}
imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));
}

if ( !preg_match('!^image/!', get_post_mime_type( $attachment )) || !file_is_displayable_image( $file ) ) return $metadata;

基本的语法

//生成水印后的图片
@unlink($groundImage);
switch($ground_info[2])//取得背景图片的格式
{
case 1:imagegif($ground_im,$groundImage);break;
case 2:imagejpeg($ground_im,$groundImage);break;
case 3:imagepng($ground_im,$groundImage);break;
default:die($errorMsg);
}

global $_wp_additional_image_sizes;

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 )

//释放内存
if(isset($water_info)) unset($water_info);
if(isset($water_im)) imagedestroy($water_im);
unset($ground_info);
imagedestroy($ground_im);
}
//—————————————————————————————
$id=$_REQUEST['id'];
$num = count($_FILES['userfile']['name']);
print_r($_FILES['userfile']);
print_r($_FILES['userfile']['name']);

foreach ( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => FALSE );
if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
$sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
else
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
$sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
else
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
$sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop'];
else
$sizes[$s]['crop'] = get_option( "{$s}_crop" );
}

参数说明: 参数 说明

echo $num;
echo “<bR>”;
if(isset($id)){
for($i=0;$i<$id;$i++){

foreach ( $sizes as $size => $size_data ) {
$resized = bt_image_make_intermediate_size( $file, $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}

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 时,实际上什么也没做,反之完全合并。

if(isset($_FILES) && !emptyempty($_FILES['userfile']) && $_FILES['userfile']['size']>0)
{
$uploadfile = “./”.time().”_”.$_FILES['userfile'][name][$i];
echo “<br>”;
echo $uploadfile;
if (copy($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
echo “OK<br>”;

return $metadata;
}

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

//文字水印
//imageWaterMark($uploadfile,5,”",”HTTP://www.lvye.info”,5,”#cccccc“);

/**
* Resize an image to make a thumbnail or intermediate size.
*
* The returned array has the file size, the image width, and image height. The
* filter 'image_make_intermediate_size' can be used to hook in and change the
* values of the returned array. The only parameter is the resized file path.
*
* @param string $file File path.
* @param int $width Image width.
* @param int $height Image height.
* @param bool|array $crop Optional, default is false. Whether to crop image to specified height and width or resize. An array can specify positioning of the crop area.
* @return bool|array False, if no image was created. Metadata array on success.
*/
function bt_image_make_intermediate_size( $file, $width, $height, $crop = false ) {
if ( $width || $height ) {
$resized_file = bt_image_resize( $file, $width, $height, $crop, null, null, 90 );
if ( !is_wp_error( $resized_file ) && $resized_file && $info = getimagesize( $resized_file ) ) {
$resized_file = apply_filters('image_make_intermediate_size', $resized_file);
return array(
'file' => wp_basename( $resized_file ),
'width' => $info[0],
'height' => $info[1],
);
}
}
return false;
}

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

//图片水印
$waterImage=”logo_ok1.gif”;//水印图片路径
imageWaterMark($uploadfile,9,$waterImage);

/**
* Retrieve calculated resized dimensions for use in imagecopyresampled().
*
* Calculate dimensions and coordinates for a resized image that fits within a
* specified width and height. If $crop is true, the largest matching central
* portion of the image will be cropped out and resized to the required size.
*
* @param int $orig_w Original width.
* @param int $orig_h Original height.
* @param int $dest_w New width.
* @param int $dest_h New height.
* @param bool $crop Optional, default is false. Whether to crop image or resize.
* @return bool|array False, on failure. Returned array matches parameters for imagecopyresampled() PHP function.
*/
function bt_image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {

 代码如下

echo “<img src=”".$uploadfile.”” border=”0”>”;
}
else
{
echo “Fail<br>”;
}
}
}
}

if ($orig_w <= 0 || $orig_h <= 0)
return false;
// at least one of dest_w or dest_h must be specific
if ($dest_w <= 0 && $dest_h <= 0)
return false;

复制代码

?>
<form enctype=”multipart/form-data” method=”POST”>
<?php
for($a=0;$a<$id;$a++){
echo “文件: <input name=”userfile[]” type=”file”><br>”;

if ( $crop ) {
// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
$aspect_ratio = $orig_w / $orig_h;
$new_w = min($dest_w, $orig_w);
$new_h = min($dest_h, $orig_h);

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

}
?>
<input type=”submit” value=”上传”>
</form>
?>

if ( !$new_w ) {
$new_w = intval($new_h * $aspect_ratio);
}

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

//下面这段代码是一段图片上传并且给上传的图片加水印

if ( !$new_h ) {
$new_h = intval($new_w / $aspect_ratio);
}

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

参数说明:
$max_file_size  : 上传文件大小限制, 单位BYTE
$destination_folder : 上传文件路径
$watermark   : 是否附加水印(1为加水印,其他为不加水印);
使用说明:
1. 将PHP.INI文件里面的"extension=php_gd2.dll"一行前面的;号去掉,因为我们要用到GD库;

$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);

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

  1. 将extension_dir =改为你的php_gd2.dll所在目录;
    3. http://www.111cn.net/php.asp;
    ****************************************************/
    //上传文件类型列表
    $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="";  //水印字符串
    $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 "图片不存在www.111cn.net!";
             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="图片预览: 文件名:".$destination." www.111cn.net上传时间:">";
        }
    }
    ?>

$crop_w = round($new_w / $size_ratio);
$crop_h = round($new_h / $size_ratio);

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

if ( !is_array( $crop ) || count( $crop ) != 2 ) {
$crop = apply_filters( 'image_resize_crop_default', array( 'center', 'center' ) );
}

//合并水印图片
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);

switch ( $crop[0] ) {
case 'left': $s_x = 0; break;
case 'right': $s_x = $orig_w - $crop_w; break;
default: $s_x = floor( ( $orig_w - $crop_w ) / 2 );
}

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

switch ( $crop[1] ) {
case 'top': $s_y = 0; break;
case 'bottom': $s_y = $orig_h - $crop_h; break;
default: $s_y = floor( ( $orig_h - $crop_h ) / 2 );
}
} else {
// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
$crop_w = $orig_w;
$crop_h = $orig_h;

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

$s_x = 0;
$s_y = 0;

//增加水印
$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); 
}

list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
}

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

// if the resulting image would be the same size or larger we don't want to resize it
if ( $new_w >= $orig_w && $new_h >= $orig_h )
return false;

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

// the return array matches the parameters to imagecopyresampled()
// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );

 代码如下

}

复制代码

/**
* Scale down an image to fit a particular size and save a new copy of the image.
*
* The PNG transparency will be preserved using the function, as well as the
* image type. If the file going in is PNG, then the resized image is going to
* be PNG. The only supported image types are PNG, GIF, and JPEG.
*
* Some functionality requires API to exist, so some PHP version may lose out
* support. This is not the fault of WordPress (where functionality is
* downgraded, not actual defects), but of your PHP version.
*
* @since 2.5.0
*
* @param string $file Image file path.
* @param int $max_w Maximum width to resize to.
* @param int $max_h Maximum height to resize to.
* @param bool $crop Optional. Whether to crop image or resize.
* @param string $suffix Optional. File Suffix.
* @param string $dest_path Optional. New image file path.
* @param int $jpeg_quality Optional, default is 90. Image quality percentage.
* @return mixed WP_Error on failure. String with new destination path.
*/
function bt_image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {

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'],

$image = wp_load_image( $file );
if ( !is_resource( $image ) )
return new WP_Error( 'error_loading_image', $image, $file );

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

$size = @getimagesize( $file );
if ( !$size )
return new WP_Error('invalid_image', __('Could not read image size'), $file);
list($orig_w, $orig_h, $orig_type) = $size;

原文地址:

// Rotate if EXIF 'Orientation' is set
// This code is from the reverted patch at
//
$rotate = false;
if ( is_callable( 'exif_read_data' ) && in_array( $orig_type, apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ) ) ) {
$exif = @exif_read_data( $file, null, true );
if ( $exif && isset( $exif['IFD0'] ) && is_array( $exif['IFD0'] ) && isset( $exif['IFD0']['Orientation'] ) ) {
if ( 6 == $exif['IFD0']['Orientation'] )
$rotate = 90;
elseif ( 8 == $exif['IFD0']['Orientation'] )
$rotate = 270;
}
}

if ( $rotate )
list($max_h,$max_w) = array($max_w,$max_h);

$dims = bt_image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
if ( !$dims )
return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;

$newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );

if ( $rotate )
list($src_y,$src_x) = array($src_x,$src_y);

imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

// convert from full colors to index colors, like original PNG.
if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );

// we don't need the original in memory anymore
imagedestroy( $image );

// $suffix will be appended to the destination filename, just before the extension
if ( !$suffix ) {
if ( $rotate )
$suffix = "{$dst_h}x{$dst_w}";
else
$suffix = "{$dst_w}x{$dst_h}";
}

$info = pathinfo($file);
$dir = $info['dirname'];
$ext = $info['extension'];
$name = wp_basename($file, ".$ext");

if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
$dir = $_dest_path;
$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";

if ( IMAGETYPE_GIF == $orig_type ) {
if ( !imagegif( $newimage, $destfilename ) )
return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
} elseif ( IMAGETYPE_PNG == $orig_type ) {
if ( !imagepng( $newimage, $destfilename ) )
return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
} else {
if ( $rotate ) {
$newimage = _rotate_image_resource( $newimage, 360 - $rotate );
}

// all other formats are converted to jpg
$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
$return = imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) );
if ( !$return )
return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
}

imagedestroy( $newimage );

// Set correct file permissions
$stat = stat( dirname( $destfilename ));
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
@ chmod( $destfilename, $perms );

return $destfilename;
}

这种方法需要你用bt_add_image_size代替原来我们习惯的add_image_size,具体的使用方法我们就不详细解释,总之这个函数给出了第三个参数,让你可以规定裁剪的开始位置。

而实际上,更为简洁的方法是,我找到一个插件,似乎可以实现这个功能,你不妨下载尝试。

Shailan.com Staff则提供了一个更直接的方法,就是修改wordpress系统文件/wp-includes/media.php,找到:

复制代码代码如下:
$s_x = floor( ($orig_w - $crop_w) / 2 );
$s_y = floor( ($orig_h - $crop_h) / 2 );

把其中的$s_y修改为:

复制代码代码如下:
$s_y = 0;// 或者你想要的值

总之,这种方法直接有效且最容易令人理解,因为$s_x和$s_y就是wordpress系统在裁剪时,裁剪区域的起始位置。而且他还推荐了一个插件:Regenerate Thumbnails,应是基于这种方法来实现的。

在stackexchange社区还有人用这样的方法更加便捷,或许你可以借鉴,但是否奏效还需要验证:

复制代码代码如下:
add_filter('wp_generate_attachment_metadata', 'custom_crop');

function custom_crop($metadata) {

$uploads = wp_upload_dir();
$file = path_join( $uploads['basedir'], $metadata['file'] ); // original image file
list( $year, $month ) = explode( '/', $metadata['file'] );
$target = path_join( $uploads['basedir'], "{$year}/{$month}/".$metadata['sizes']['medium']['file'] ); // intermediate size file
$image = imagecreatefromjpeg($file); // original image resource
$image_target = wp_imagecreatetruecolor( 44, 44 ); // blank image to fill
imagecopyresampled($image_target, $image, 0, 0, 25, 15, 44, 44, 170, 170); // crop original
imagejpeg($image_target, $target, apply_filters( 'jpeg_quality', 90, 'image_resize' )); // write cropped to file

return $metadata;
}

本文由10bet手机官网发布于面向对象,转载请注明出处:图像添加水印,php给图片加水印与上传图片加水印php类

上一篇:CMS功能进一步增强,9新功能小结 下一篇:PHP调用MYSQL存储过程实例,php怎么运行存储过程
猜你喜欢
热门排行
精彩图文