search
HomeBackend DevelopmentPHP TutorialUsage of php general image processing class

Usage of php general image processing class

Jun 12, 2018 am 09:39 AM
phppicturedeal withkindUniversal

This article mainly introduces the general image processing class implemented by PHP, which can realize functions such as zooming, cutting, photo frames, watermarks, sharpening, rotation, flipping, transparency, and inversion of images. It has certain reference value. , Friends who need it can refer to

The examples in this article describe the general image processing class implemented by PHP. Share it with everyone for your reference. The details are as follows:

The image processing function functions: zoom, cut, photo frame, watermark, sharpen, rotate, flip, transparency, invert color, the idea of ​​​​processing and saving historical records: when a picture is changed Automatically generate a new picture. The naming method can consider adding steps based on the original picture, for example: picture name __ what step. In some web applications that require advanced image processing functions, you can refer to this class.

<?php
class picture
{
  var $PICTURE_URL;//要处理的图片
  var $DEST_URL="temp__01.jpg";//生成目标图片位置
  var $PICTURE_CREATE;//要创建的图片
  var $TURE_COLOR;//新建一个真彩图象
  var $PICTURE_WIDTH;//原图片宽度
  var $PICTURE_HEIGHT;//原图片高度
/*
水印的类型,默认的为水印文字
*/
  var $MARK_TYPE=1;
  var $WORD;//经过UTF-8后的文字
  var $WORD_X;//文字横坐标
  var $WORD_Y;//文字纵坐标
  var $FONT_TYPE;//字体类型
  var $FONT_SIZE="12";//字体大小
  var $FONT_WORD;//文字
  var $ANGLE=0;//文字的角度,默认为0
  var $FONT_COLOR="#000000";//文字颜色
  var $FONT_PATH="font/simkai.ttf";//字体库,默认为宋体
  var $FORCE_URL;//水印图片
  var $FORCE_X=0;//水印横坐标
  var $FORCE_Y=0;//水印纵坐标
  var $FORCE_START_X=0;//切起水印的图片横坐标
  var $FORCE_START_Y=0;//切起水印的图片纵坐标
  var $PICTURE_TYPE;//图片类型
  var $PICTURE_MIME;//输出的头部
/*
缩放比例为1的话就按缩放高度和宽度缩放
*/
  var $ZOOM=1;//缩放类型
  var $ZOOM_MULTIPLE;//缩放比例
  var $ZOOM_WIDTH;//缩放宽度
  var $ZOOM_HEIGHT;//缩放高度
/*
裁切,按比例和固定长度、宽度
*/
  var $CUT_TYPE=1;//裁切类型
  var $CUT_X=0;//裁切的横坐标
  var $CUT_Y=0;//裁切的纵坐标
  var $CUT_;//裁切的宽度
  var $CUT_HEIGHT=100;//裁切的高度
/*
锐化
*/
  var $SHARP="7.0";//锐化程度
/*
透明度处理
*/
  var $ALPHA=&#39;100&#39;;//透明度在0-127之间
  var $ALPHA_X="90";
  var $ALPHA_Y="50";
/*
任意角度旋转
*/
  var $CIRCUMROTATE="90.0";//注意,必须为浮点数
/*
出错信息
*/
  var $ERROR=array(
    &#39;unalviable&#39;=>&#39;没有找到相关图片!&#39;
  );
/*
构造函数:函数初始化
*/
  function __construct($PICTURE_URL)
  {
    $this->get_info($PICTURE_URL);
  }
  function get_info($PICTURE_URL)
  {
    /*
    处理原图片的信息,先检测图片是否存在,不存在则给出相应的信息
    */
    @$SIZE=getimagesize($PICTURE_URL);
    if(!$SIZE)
    {
      exit($this->ERROR[&#39;unalviable&#39;]);
    }
    //得到原图片的信息类型、宽度、高度
    $this->PICTURE_MIME=$SIZE[&#39;mime&#39;];
    $this->PICTURE_;
    $this->PICTURE_HEIGHT=$SIZE[1];
    //创建图片
    switch($SIZE[2])
    {
      case 1:
        $this->PICTURE_CREATE=imagecreatefromgif($PICTURE_URL);
        $this->PICTURE_TYPE="imagejpeg";
        $this->PICTURE_EXT="jpg";
        break;
      case 2:
        $this->PICTURE_CREATE=imagecreatefromjpeg($PICTURE_URL);
        $this->PICTURE_TYPE="imagegif";
        $this->PICTURE_EXT="gif";
        break;
      case 3:
        $this->PICTURE_CREATE=imagecreatefrompng($PICTURE_URL);
        $this->PICTURE_TYPE="imagepng";
        $this->PICTURE_EXT="png";
        break;
    } 
    /*
    文字颜色转换16进制转换成10进制
    */
    preg_match_all("/([0-f]){2,2}/i",$this->FONT_COLOR,$MATCHES);
    if(count($MATCHES)==3)
    {
      $this->RED=hexdec($MATCHES[0][0]);
      $this->GREEN=hexdec($MATCHES[0][1]);
      $this->BLUE=hexdec($MATCHES[0][2]);
    }
  }
  //end of __construct
  /*
  将16进制的颜色转换成10进制的(R,G,B)
  */
  function hex2dec()
  {
    preg_match_all("/([0-f]){2,2}/i",$this->FONT_COLOR,$MATCHES);
    if(count($MATCHES)==3)
    {
      $this->RED=hexdec($MATCHES[0][0]);
      $this->GREEN=hexdec($MATCHES[0][1]);
      $this->BLUE=hexdec($MATCHES[0][2]);
    }
  }
  //缩放类型
  function zoom_type($ZOOM_TYPE)
  {
    $this->ZOOM=$ZOOM_TYPE;
  }
  //对图片进行缩放,如果不指定高度和宽度就进行缩放
  function zoom()
  {
    //缩放的大小
    if($this->ZOOM==0)
    {
      $this->ZOOM_;gt;PICTURE_WIDTH * $this->ZOOM_MULTIPLE;
      $this->ZOOM_HEIGHT=$this->PICTURE_HEIGHT * $this->ZOOM_MULTIPLE;
    }
    //新建一个真彩图象
    $this->TRUE_COLOR=imagecreatetruecolor($this->ZOOM_WIDTH,$this->ZOOM_HEIGHT);
    $WHITE=imagecolorallocate($this->TRUE_COLOR,255,255,255);
    imagefilledrectangle($this->TRUE_COLOR,0,0,$this->ZOOM_WIDTH,$this->ZOOM_HEIGHT,$WHITE);
    imagecopyresized($this->TRUE_COLOR,$this->PICTURE_CREATE,0,0,0,0,$this->ZOOM_WIDTH,$this->ZOOM_HEIGHT,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  }
  //end of zoom
  //裁切图片,按坐标或自动
  function cut()
  {
    $this->TRUE_COLOR=imagecreatetruecolor($this->CUT_WIDTH,$this->CUT_WIDTH);
    imagecopy($this->TRUE_COLOR,$this->PICTURE_CREATE, 0, 0, $this->CUT_X, $this->CUT_Y,$this->CUT_WIDTH,$this->CUT_HEIGHT);
  }
  //end of cut
  /*
  在图片上放文字或图片
  水印文字
  */
  function _mark_text()
  {
    $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
    $this->WORD=mb_convert_encoding($this->FONT_WORD,&#39;utf-8&#39;,&#39;gb2312&#39;);
    /*
    取得使用 TrueType 字体的文本的范围
    */
    $TEMP = imagettfbbox($this->FONT_SIZE,0,$this->FONT_PATH,$this->WORD);
    $WORD_LENGTH=strlen($this->WORD);
    $WORD_WIDTH =$TEMP[2] - $TEMP[6];
    $WORD_HEIGHT =$TEMP[3] - $TEMP[7];
    /*
    文字水印的默认位置为右下角
    */
    if($this->WORD_X=="")
    {
      $this->WORD_X=$this->PICTURE_WIDTH-$WORD_WIDTH;
    }
    if($this->WORD_Y=="")
    {
      $this->WORD_Y=$this->PICTURE_HEIGHT-$WORD_HEIGHT;
    }
    imagesettile($this->TRUE_COLOR,$this->PICTURE_CREATE);
    imagefilledrectangle($this->TRUE_COLOR,0,0,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT,IMG_COLOR_TILED);
    $TEXT2=imagecolorallocate($this->TRUE_COLOR,$this->RED,$this->GREEN,$this->Blue);
    imagettftext($this->TRUE_COLOR,$this->FONT_SIZE,$this->ANGLE,$this->WORD_X,$this->WORD_Y,$TEXT2,$this->FONT_PATH,$this->WORD);
  }
  /*
  水印图片
  */
function _mark_picture()
{
  /*
  获取水印图片的信息
  */
  @$SIZE=getimagesize($this->FORCE_URL);
  if(!$SIZE)
  {
    exit($this->ERROR[&#39;unalviable&#39;]);
  }
  $FORCE_PICTURE_;
  $FORCE_PICTURE_HEIGHT=$SIZE[1];
  //创建水印图片
  switch($SIZE[2])
  {
    case 1:
      $FORCE_PICTURE_CREATE=imagecreatefromgif($this->FORCE_URL);
      $FORCE_PICTURE_TYPE="gif";
      break;
    case 2:
      $FORCE_PICTURE_CREATE=imagecreatefromjpeg($this->FORCE_URL);
      $FORCE_PICTURE_TYPE="jpg";
      break;
    case 3:
      $FORCE_PICTURE_CREATE=imagecreatefrompng($this->FORCE_URL);
      $FORCE_PICTURE_TYPE="png";
      break;
  }
/*
  判断水印图片的大小,并生成目标图片的大小,如果水印比图片大,则生成图片大小为水印图片的大小。否则生成的图片大小为原图片大小。
*/
  $this->NEW_PICTURE=$this->PICTURE_CREATE;
  if($FORCE_PICTURE_WIDTH>$this->PICTURE_WIDTH)
  {
    $CREATE_;gt;FORCE_START_X;
  }
  else
  {
    $CREATE_;gt;PICTURE_WIDTH;
  }
  if($FORCE_PICTURE_HEIGHT>$this->PICTURE_HEIGHT)
  {
    $CREATE_HEIGHT=$FORCE_PICTURE_HEIGHT-$this->FORCE_START_Y;
  }
  else
  {
    $CREATE_HEIGHT=$this->PICTURE_HEIGHT;
  }
  /*
  创建一个画布
  */
  $NEW_PICTURE_CREATE=imagecreatetruecolor($CREATE_WIDTH,$CREATE_HEIGHT);
  $WHITE=imagecolorallocate($NEW_PICTURE_CREATE,255,255,255);
  /*
  将背景图拷贝到画布中
  */
  imagecopy($NEW_PICTURE_CREATE, $this->PICTURE_CREATE, 0, 0, 0, 0,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  /*
  将目标图片拷贝到背景图片上
  */
  imagecopy($NEW_PICTURE_CREATE, $FORCE_PICTURE_CREATE, $this->FORCE_X, $this->FORCE_Y, $this->FORCE_START_X, $this->FORCE_START_Y,$FORCE_PICTURE_WIDTH,$FORCE_PICTURE_HEIGHT);
  $this->TRUE_COLOR=$NEW_PICTURE_CREATE;
}
//end of mark
function alpha_()
{
  $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  $rgb="#CDCDCD";
  $tran_color="#000000";
  for($j=0;$j<=$this->PICTURE_HEIGHT-1;$j++)
  {
    for ($i=0;$i<=$this->PICTURE_WIDTH-1;$i++)
    {
      $rgb = imagecolorat($this->PICTURE_CREATE,$i,$j);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      $now_color=imagecolorallocate($this->PICTURE_CREATE,$r,$g,$b);
      if ($now_color==$tran_color)
      {
        continue;
      }
      else
      {
        $color=imagecolorallocatealpha($this->PICTURE_CREATE,$r,$g,$b,$ALPHA);
        imagesetpixel($this->PICTURE_CREATE,$ALPHA_X+$i,$ALPHA_Y+$j,$color);
      }
      $this->TRUE_COLOR=$this->PICTURE_CREATE;
    }
  }
}
/*
图片旋转:
沿y轴旋转
*/
function turn_y()
{
  $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  for ($x = 0; $x < $this->PICTURE_WIDTH; $x++)
  {
    imagecopy($this->TRUE_COLOR, $this->PICTURE_CREATE, $this->PICTURE_WIDTH - $x - 1, 0, $x, 0, 1, $this->PICTURE_HEIGHT);
  }
}
/*
沿X轴旋转
*/
function turn_x()
{
  $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  for ($y = 0; $y < $this->PICTURE_HEIGHT; $y++)
  {
    imagecopy($this->TRUE_COLOR, $this->PICTURE_CREATE, 0, $this->PICTURE_HEIGHT - $y - 1, 0, $y, $this->PICTURE_WIDTH, 1);
  }
}
/*
任意角度旋转
*/
function turn()
{
  $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  imageCopyResized($this->TRUE_COLOR,$this->PICTURE_CREATE,0,0,0,0,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  $WHITE=imagecolorallocate($this->TRUE_COLOR,255,255,255);
  $this->TRUE_COLOR=imagerotate ($this->TRUE_COLOR, $this->CIRCUMROTATE, $WHITE);
}
/*
图片锐化
*/
function sharp()
{
  $this->TRUE_COLOR=imagecreatetruecolor($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  $cnt=0;
  for ($x=0; $x<$this->PICTURE_WIDTH; $x++)
  {
    for ($y=0; $y<$this->PICTURE_HEIGHT; $y++)
    {
      $src_clr1 = imagecolorsforindex($this->TRUE_COLOR, imagecolorat($this->PICTURE_CREATE, $x-1, $y-1));
      $src_clr2 = imagecolorsforindex($this->TRUE_COLOR, imagecolorat($this->PICTURE_CREATE, $x, $y));
      $r = intval($src_clr2["red"]+$this->SHARP*($src_clr2["red"]-$src_clr1["red"]));
      $g = intval($src_clr2["green"]+$this->SHARP*($src_clr2["green"]-$src_clr1["green"]));
      $b = intval($src_clr2["blue"]+$this->SHARP*($src_clr2["blue"]-$src_clr1["blue"]));
      $r = min(255, max($r, 0));
      $g = min(255, max($g, 0));
      $b = min(255, max($b, 0));
      if (($DST_CLR=imagecolorexact($this->PICTURE_CREATE, $r, $g, $b))==-1)
        $DST_CLR = imagecolorallocate($this->PICTURE_CREATE, $r, $g, $b);
        $cnt++;
      if ($DST_CLR==-1) die("color allocate faile at $x, $y ($cnt).");
        imagesetpixel($this->TRUE_COLOR, $x, $y, $DST_CLR);
    }
  }
}
/*
  将图片反色处理??
*/
function return_color()
{
  /*
  创建一个画布
  */
  $NEW_PICTURE_CREATE=imagecreate($this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  $WHITE=imagecolorallocate($NEW_PICTURE_CREATE,255,255,255);
  /*
  将背景图拷贝到画布中
  */
  imagecopy($NEW_PICTURE_CREATE, $this->PICTURE_CREATE, 0, 0, 0, 0,$this->PICTURE_WIDTH,$this->PICTURE_HEIGHT);
  $this->TRUE_COLOR=$NEW_PICTURE_CREATE;
}
/*
生成目标图片并显示
*/
function show()
{
  // 判断浏览器,若是IE就不发送头
  if(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;]))
  {
    $ua = strtoupper($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
    if(!preg_match(&#39;/^.*MSIE.*\)$/i&#39;,$ua))
    {
      header("Content-type:$this->PICTURE_MIME");
    }
  }
  $OUT=$this->PICTURE_TYPE;
  $OUT($this->TRUE_COLOR);
}
/*
生成目标图片并保存
*/
function save_picture()
{
  // 以 JPEG 格式将图像输出到浏览器或文件
  $OUT=$this->PICTURE_TYPE;
  if(function_exists($OUT))
  {
    // 判断浏览器,若是IE就不发送头
    if(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;]))
    {
      $ua = strtoupper($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
      if(!preg_match(&#39;/^.*MSIE.*\)$/i&#39;,$ua))
      {
        header("Content-type:$this->PICTURE_MIME");
      }
    }
    if(!$this->TRUE_COLOR)
    {
      exit($this->ERROR[&#39;unavilable&#39;]);
    }
    else
    {
      $OUT($this->TRUE_COLOR,$this->DEST_URL);
      $OUT($this->TRUE_COLOR);
    }
  }
}
/*
析构函数:释放图片
*/
function __destruct()
{
/*释放图片*/
  imagedestroy($this->TRUE_COLOR);
  imagedestroy($this->PICTURE_CREATE);
}
//end of class
}
?>

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php custom array variables store time zone information around the world

A simple implementation method for PHP to generate a specified random string _php skills

php array calling and function execution methods

The above is the detailed content of Usage of php general image processing class. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.