Home Backend Development PHP Tutorial php实现给一张图片加上水印效果_php实例

php实现给一张图片加上水印效果_php实例

Jun 07, 2016 pm 05:10 PM

php实现给一张图片加上水印效果

<&#63;php
/**
 * 功能:给一张图片加上水印效果
 *      $i 要加水印效果的图片
 *      $t 水印文字
 *      $size 文字大小
 *      $pos 水印的位置
 *      $color 文字的颜色
 *      $flag 是布尔值,主要用来区分是不是原图上加水印
 *      $type 如果$flag等于false 则新图上加上水印 新文件名为 原名_txt.jpg
 */
function txt($i,$t='版权所有',$size=25,$pos=5,$color='rand',$flag=true,$type='_txt'){
  $img = imagecreatefromjpeg($i);
  $w = imagesx($img);
  $h = imagesy($img);
  $font = dirname(__FILE__).'/font/ls.ttf';
  $ps = imagettfbbox($size,0,$font,$t);
  $tw = $ps[4];
  $th = abs($ps[5]);
  switch($pos){
    case 1:break;  
    case 2:break;  
    case 3:break;  
    case 4:break;  
    case 5:$x=($w-$tw)/2;$y=($h-$th)/2+$th;break;  
    case 6:break;  
    case 7:break;  
    case 8:break;  
    case 9:break;  
    default:break;
  }
  $c = getcolor($img,$color);
  imagettftext($img,$size,0,$x,$y,$c,$font,$t);
  if($flag){
    imagejpeg($img,$i); 
  }else{
    $ext = ext($i);
    $ppp = rtrim($i,'.'.$ext);
    $ppp = $ppp.$type.'.'.$ext;
    imagejpeg($img,$ppp);
  }
}
 
function getcolor($i,$c='rand',$a=50){
  $cc = '';
  switch($c){
    case 'white':$cc=imagecolorallocatealpha($i,255,255,255,$a);break;
    case 'black':$cc=imagecolorallocatealpha($i,0,0,0,$a);break;
    case 'red':$cc=imagecolorallocatealpha($i,255,0,0,$a);break;
    case 'green':$cc=imagecolorallocatealpha($i,0,255,0,$a);break;
    case 'blue':$cc=imagecolorallocatealpha($i,0,0,255,$a);break;
    case 'orange':$cc=imagecolorallocatealpha($i,0xff,0x66,0x33,$a);break;
    case 'yellow':$cc=imagecolorallocatealpha($i,255,255,0,$a);break;
    case 'rand':$cc=imagecolorallocatealpha($i,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255),$a);break;
    default:
      $cs = substr($c,1);
      $ok = str_split($cs,2);
      $cc = imagecolorallocatealpha($i,hexdec($ok[0]),hexdec($ok[1]),hexdec($ok[2]),$a);
    break;   
  }
  return $cc;
}
 
 
/**
 * 功能是:返回扩展名
 */
 
function ext($f){
  $exts = explode('.',$f);
  return end($exts);
}
 
/**
 * 功能是:返回文件名,不含扩展名
 */
function name($f){
  $s = explode('/',$f);
  $fn = end($s);
  return rtrim($fn,'.'.ext($f));
}
Copy after login

我们再来看一个支持以图片和文字两种方式给图片添加水印。图片支持GIF,PNG,JPG三种格式,水印图片支持PNG和GIF

function setWater($imgSrc,$markImg,$markText,$TextColor,$markPos,$fontType,$markType)
{

  $srcInfo = @getimagesize($imgSrc);
  $srcImg_w  = $srcInfo[0];
  $srcImg_h  = $srcInfo[1];
    
  switch ($srcInfo[2]) 
  { 
    case 1: 
      $srcim =imagecreatefromgif($imgSrc); 
      break; 
    case 2: 
      $srcim =imagecreatefromjpeg($imgSrc); 
      break; 
    case 3: 
      $srcim =imagecreatefrompng($imgSrc); 
      break; 
    default: 
      die("不支持的图片文件类型"); 
      exit; 
  }
    
  if(!strcmp($markType,"img"))
  {
    if(!file_exists($markImg) || empty($markImg))
    {
      return;
    }
      
    $markImgInfo = @getimagesize($markImg);
    $markImg_w  = $markImgInfo[0];
    $markImg_h  = $markImgInfo[1];
      
    if($srcImg_w < $markImg_w || $srcImg_h < $markImg_h)
    {
      return;
    }
      
    switch ($markImgInfo[2]) 
    { 
      case 1: 
        $markim =imagecreatefromgif($markImg); 
        break; 
      case 2: 
        $markim =imagecreatefromjpeg($markImg); 
        break; 
      case 3: 
        $markim =imagecreatefrompng($markImg); 
        break; 
      default: 
        die("不支持的水印图片文件类型"); 
        exit; 
    }
      
    $logow = $markImg_w;
    $logoh = $markImg_h;
  }
    
  if(!strcmp($markType,"text"))
  {
    $fontSize = 16;
    if(!empty($markText))
    {
      if(!file_exists($fontType))
      {
        return;
      }
    }
    else {
      return;
    }
      
    $box = @imagettfbbox($fontSize, 0, $fontType,$markText);
    $logow = max($box[2], $box[4]) - min($box[0], $box[6]);
    $logoh = max($box[1], $box[3]) - min($box[5], $box[7]);
  }
    
  if($markPos == 0)
  {
    $markPos = rand(1, 9);
  }
    
  switch($markPos)
  {
    case 1:
      $x = +5;
      $y = +5;
      break;
    case 2:
      $x = ($srcImg_w - $logow) / 2;
      $y = +5;
      break;
    case 3:
      $x = $srcImg_w - $logow - 5;
      $y = +15;
      break;
    case 4:
      $x = +5;
      $y = ($srcImg_h - $logoh) / 2;
      break;
    case 5:
      $x = ($srcImg_w - $logow) / 2;
      $y = ($srcImg_h - $logoh) / 2;
      break;
    case 6:
      $x = $srcImg_w - $logow - 5;
      $y = ($srcImg_h - $logoh) / 2;
      break;
    case 7:
      $x = +5;
      $y = $srcImg_h - $logoh - 5;
      break;
    case 8:
      $x = ($srcImg_w - $logow) / 2;
      $y = $srcImg_h - $logoh - 5;
      break;
    case 9:
      $x = $srcImg_w - $logow - 5;
      $y = $srcImg_h - $logoh -5;
      break;
    default: 
      die("此位置不支持"); 
      exit;
  }
    
  $dst_img = @imagecreatetruecolor($srcImg_w, $srcImg_h);
    
  imagecopy ( $dst_img, $srcim, 0, 0, 0, 0, $srcImg_w, $srcImg_h);
    
  if(!strcmp($markType,"img"))
  {
    imagecopy($dst_img, $markim, $x, $y, 0, 0, $logow, $logoh);
    imagedestroy($markim);
  }
    
  if(!strcmp($markType,"text"))
  {
    $rgb = explode(',', $TextColor);
      
    $color = imagecolorallocate($dst_img, $rgb[0], $rgb[1], $rgb[2]);
    imagettftext($dst_img, $fontSize, 0, $x, $y, $color, $fontType,$markText);
  }
    
  switch ($srcInfo[2]) 
  { 
    case 1:
      imagegif($dst_img, $imgSrc); 
      break; 
    case 2: 
      imagejpeg($dst_img, $imgSrc); 
      break; 
    case 3: 
      imagepng($dst_img, $imgSrc); 
      break;
    default: 
      die("不支持的水印图片文件类型"); 
      exit; 
  }
    
  imagedestroy($dst_img);
  imagedestroy($srcim);
}

Copy after login

参数说明:

$imgSrc:目标图片,可带相对目录地址,
$markImg:水印图片,可带相对目录地址,支持PNG和GIF两种格式,如水印图片在执行文件mark目录下,可写成:mark/mark.gif
$markText:给图片添加的水印文字
$TextColor:水印文字的字体颜色
$markPos:图片水印添加的位置,取值范围:0~9
0:随机位置,在1~8之间随机选取一个位置
1:顶部居左 2:顶部居中 3:顶部居右 4:左边居中
5:图片中心 6:右边居中 7:底部居左 8:底部居中 9:底部居右
$fontType:具体的字体库,可带相对目录地址
$markType:图片添加水印的方式,img代表以图片方式,text代表以文字方式添加水印

代码注释:

第4~6行:获取目标图片的宽度和高度
第8~22行:根据图片类型调用不同的函数,获得操作图像标识符

GetImageSize函数知识点:GetImageSize不需要安装 GD度就可使用,其返回值数组有四个元素。索引值0是图片高度。索引值1是图片的宽度。索引值2是图片的文件格式,其值1为GIF格式、2为JPEG/JPG格式、3为PNG格式。索引值3为图片的高与宽字符串,height=xxx width=yyy。返回的图片宽度和高度单位都是像素(pixel)

第24~58行:当选择图片方式给目标图片添加水印时,获取水印图片的宽度和高度,通常情况都是网站的logo。如果目标图片比水印图片宽度或者高度小或者水印图片不存在,则跳出这个函数。

return语句知识点:直接return 表示什么都不返回,直接结束这个函数。也可以理解成返回 NULL。

第60~77行:当选择文字方式给目标图片添加水印时,首先设定水印文字的大小,默认我设置为16px,你可以根据需要自行调整字体大小。如果字体文件不存在,跳出函数,最后通过imagettfbbox函数获得此设定格式的文字的虚拟长宽。

imagettfbbox函数知识点:此函数返回一个含有8个单元的数组表示文本外框的四个角,索引值含义:0代表左下角 X 位置,1代表坐下角 Y 位置,2代表右下角 X 位置,3代表右下角 Y 位置,4代表右上角 X 位置,5代表右上角 Y 位置,6代表左上角 X 位置,7代表左上角 Y 位置。此函数同时需要GD 库和FreeType库的支持
max函数返回参数中数值最大的值。

第79~125行:根据设定的图片水印位置计算具体坐标值,你可以根据效果具体细化水印的位置。

第127~129行:新建一个和目标图片大小一致的图片。

注:由于imagecreatetruecolor函数范围的是一个黑色图片,所以如果你的目标图片是透明的,则生成的新图将不会是透明色。

第131~162行:根据图片或者文字方式,最终生成添加了水印的图片。

调用说明:

以函数调用方式调用即可,当然你也可以以类的方式封装,或者你也可以根据需要将此函数进一步细分模块也可以。当然你现在这样用也是没有任何问题的,我已测试过,请放心使用。

其他说明:

由于imagettftext和imagettfbbox函数需要GD库和FreeType库的支持,如果你的运行环境不支持GD库和FreeType库则文字方式就无法实现,你可以用imagestring函数实现给图片添加文字水印,同时设定下text方式下的$logow和$logoh值即可。

imagejpeg函数也可以设置合成的图片质量。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles