PHP Image processing class library and demo sharing _php example

Source: Internet
Author: User
Tags imagejpeg md5

Simply wrote a PHP image processing class library, although the function is relatively few, but at present also useless to too advanced, later used to fill it, or who to point to add what function, or what the demand can tell me, I have time to add, if this class library has been extended, Also trouble to take out to share, the code is now able to use on the line, consider not a lot of things, what better advice please tell me, thank you

img.php

<?php/** * Created by Phpstorm. * User:mction * DATE:2015/5/14 0014 * time:15:36 * Simple Image class Library, all the relative paths in this class are based on the site root directory, if you want to modify, then modify the constant __webroot__ can * function: Specify the text content creation diagram Slice (Chinese not supported), create a captcha picture, create a thumbnail, other features to be continued * Method: * Style (array $Options) set Picture style, reset to default style before each setting * Create_img_png () Create Png image, related properties by St YLE Specifies * CREATE_IMG_JPEG () to create a Jpeg image, the associated property is created by the style specified * Create_verify () to create a CAPTCHA image, and the related property is specified by the style * get_verify () to obtain the verification code value created, M D5 Encryption * LOAD_IMG (string $FilePath) loads an image, creates an image source for other methods to invoke the source, FilePath the image relative path * CREATE_THUMB (String $FileName, String $FilePa TH) Creates a thumbnail of the image loaded by load_img (), filename is the saved image prefix, filepath is the relative path to save the image, does not contain a filename (example:/uploads/images/thumb/)/if (!defined ("
 
__webroot__ ")) define (" __webroot__ ", $_server[' Document_root ')); Class IMG {protected $_img;//Picture source protected $_fileimg;//Loaded picture source protected $_fileinfo;//Loaded picture's information array protected $_PI Cinfo; Loaded picture of the wide higher information array protected $_rand = ' abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ1234567890 '; Random factor protected $_code = '; Authentication Code Public $Width = 300;//Picture default wide public $Height = 80;
  Picture Default high Public $BackgroundColor = "000000"; Public $Font = "/PHPS/PUBLIC/FONT/ARIALNB. TTF "; Default font public $FontSize = 16; Default font font size public $FontColor = "FFFFFF";
  Default font Color Public $Content = "Test Word";
  Public $Align = "Left"; Public $Codes = 4; Number of authentication codes public $Line = 6; Number of disturbing lines public $LoadErr = ';
  Error message//public function __construct () {}/** Set picture properties * @param array $Options Property arrays * @return $this return objects * *
    Public Function Style ($Options) {$this-> _re_set (); foreach ($Options as $K => $V) {if In_array ($K, Array (' Width ', ' Height ', ' backgroundcolor ', ' Font ', ' fontsize '), '
          FontColor ', ' Content ', ' Align ', ' codes ', ' line ', ' Snow ')) {if ($K = = "BackgroundColor" | | $K = = "FontColor") {
        if (Preg_match ("# ([a-za-z0-9]{6}) #", $V)) $this-> $K = $V;
        }else{$this-> $K = $V;
  }} return $this; /** * Resets properties, does not provide external access/protected function _re_set () {$this -> Width = 100;
    $this-> Height = 30;
    $this-> backgroundcolor = "000000"; $this-> Font = "/PHPS/PUBLIC/FONT/ARIALNB."
    TTF ";
    $this-> fontsize = 16;
    $this-> fontcolor = "FFFFFF";
    $this-> Align = "Left";
    $this-> codes = 4;
  $this-> line = 6; 
    /** * Create an image source, add a background, create an image * @param bool $BGC Specify whether to create a background color and a rectangular block/protected function _create_img_gb ($BGC = True) { $this-> _img = Imagecreatetruecolor ($this-> Width, $this-> Height); Create background source if ($BGC) {Preg_match ("# ([A-za-z0-9]{2}) ([A-za-z0-9]{2}) ([a-za-z0-9]{2}) #", $this-> backgroundcolor, $C Olorarr); Separates color values into three sets of 16-bit $Color = Imagecolorallocate ($this-> _img,hexdec ($COLORARR [1]), Hexdec ($COLORARR [2]), Hexdec ($Co LORARR[3])); Add background color imagefilledrectangle to the IMG image source ($this-> _img,0, $this-> Height, $this-> width,0, $Color); Create Image}/** * Create a random authentication code */protected function _create_code () {$Len = strlen ($this-> _rand)-1;
    for ($i = 0; $i < $this-> codes $i + +) {$this-> _code. = $this-> _rand[mt_rand (0, $Len)]; /** * Writes a string to the image, temporarily does not support Chinese */protected function _write_text () {$FontWidth = Imagefontwidth ($this-> FontSize); Gets the width of one character of the font size Preg_match_all ('/(.) /us ', $this-> Content, $TEXTARR); Separate the contents of the number of statistics $FontHeight = imagefontheight ($this-> fontsize); Gets the height of the font size $X = Ceil (($this-> Width-($FontWidth * COUNT ($TextArr [0])))/2); Set the distance of the left margin of the x wheelbase $Y = Ceil (($this-> Height + $FontHeight)/2);
    Sets the distance of the top margin of the Y wheelbase Preg_match ("# ([a-za-z0-9]{2}] ([a-za-z0-9]{2}) ([a-za-z0-9]{2}) #", $this-> fontcolor, $COLORARR); $Color = imagecolorallocate ($this-> _img,hexdec ($COLORARR [1]), Hexdec ($COLORARR [2]), Hexdec ($COLORARR [3])); Set text color Imagettftext ($this-> _img, $this-> fontsize,0, $X, $Y, $Color, __webroot__. $this-> Font, $this-> Co Ntent);
  Write content}/** * Write verification code to the image/protected function _write_code () {  $_x = $this-> width/$this-> codes; Set the aspect ratio for ($i = 0; $i < $this-> codes $i + +) {//Loop codes times, generate one verification code value $Color = Imagecolorallocate ($this ; _img,mt_rand (0,156), Mt_rand (0,156), Mt_rand (0,156)); Color Imagettftext ($this-> _img, $this-> Fontsize,mt_rand ( -30,30), $_x* $i +mt_rand (1,5), $this-> Hei ght/1.3, $Color, __webroot__. $this-> Font, $this-> _code[$i]); Generate a verification code value}}/** * Write interference lines to the image/protected function _write_line () {//Generate interference line for ($i =0; $i < $th
      is-> line $i + +) {$Color = Imagecolorallocate ($this-> _img,mt_rand (0,156), Mt_rand (0,156), Mt_rand (0,156)); Imageline ($this-> _img,mt_rand (0, $this-> width), mt_rand (0, $this-> Height), Mt_rand (0, $this-> width), MT
    _rand (0, $this-> Height), $Color);
    }/** * Sets the image type to Jpeg/protected function _img_jpeg () {header (' content-type:image/jpeg ');
    Imagejpeg ($this-> _img);
Imagedestroy ($this-> _img);  /** * Sets the image type to Png/protected function _img_png () {header (' content-type:image/png ');
    Imagepng ($this-> _img);
  Imagedestroy ($this-> _img);
    /** * Create JPEG string image */Public Function create_img_jpg () {$this-> _create_img_gb (True);
    $this-> _write_text ();
  $this-> _img_jpeg ();
    /** * Create Png string image/Public function create_img_png () {$this-> _create_img_gb (True);
    $this-> _write_text ();
  $this-> _img_png ();
    /** * Create Authenticode PNG image/Public Function create_verify () {$this-> backgroundcolor = ';
    for ($I = 0; $I < 3 $I + +) {$this-> backgroundcolor. = Dechex (Mt_rand (20,155));
    } $this-> _CREATE_IMG_GB (True);
    $this-> _create_code ();
    $this-> _write_line ();
    $this-> _write_code ();
  $this-> _img_png (); /** * External acquisition of MD5 encrypted verification code * @return string/Public function get_verify () {return MD5 ($this-> _code); /** * Load an image file and obtain image-related information * @param string $FilePath image relative path address * @return $this |bool Return the object successfully, otherwise return false */P
    ublic function load_img ($FilePath) {$FilePath = __webroot__. $FilePath;
      if (!is_file ($FilePath)) {$this-> loaderr = "Path error, file does not exist";
    return False;
    $this-> _picinfo = getimagesize ($FilePath);
    $this-> _fileinfo = PathInfo ($FilePath);
      Switch ($this-> _picinfo[2]) {Case 1: $this->_fileimg = Imagecreatefromgif ($FilePath);
      Case 2: $this->_fileimg = Imagecreatefromjpeg ($FilePath);
      Case 3: $this->_fileimg = Imagecreatefrompng ($FilePath); Default: $this-> loaderr = "type error, unsupported picture type";
    return False;
  return True; /** * Create thumbnail * @param string $FileName saved picture name prefix * @param string $FilePath Save picture relative path * @return Mixed return Build
    The information array of the picture/Public function Create_thumb ($FileName, $FilePath) {$SavePath = __webroot__. $FilePath; if (!file_exists ($SavePath)) {mkdir ($SavePath, 0777,true); $FileName = $FileName. Date ("Ymdhis"). Rand (100,999).
    $this-> _fileinfo[' extension '];
    $FilePath = $FilePath. $FileName;
    $SavePath = $SavePath. $FileName;
    $this-> _CREATE_IMG_GB (False); Imagecopyresampled ($this-> _img, $this-> _fileimg,0,0,0,0, $this-> Width, $this-> Height, $this-> _
    Picinfo[0], $this-> _picinfo[1]);
      Switch ($this-> _picinfo[2]) {case 1:imagegif ($this-> _img, $SavePath);
      Case 2:imagejpeg ($this-> _img, $SavePath);
    Case 3:imagepng ($this-> _img, $SavePath);
    $FIleInfo [' FileName '] = $FileName;
    $FIleInfo [' FilePath '] = $FilePath;
  return $FIleInfo;

 }
}

Using the sample

$IMG = new Img ();
 
$Options [' Width '] =;
$Options [' Height '] = m;
$Options [' Content '] = "Test Create Img";
$Options [' fontcolor '] = "FF0000";
$Options [' backgroundcolor '] = "aaaaaa";
$IMG-> Style ($Options)-> create_img_jpg ();
 
if ($Img-> load_img ("/public/images/ad1.png")) {
  $FileInfo = $Img-> Style (Array (' Width ' =>30, ' Height ' = >30))-> create_thumb ("Thumb", "/uploads/images/");
  Var_dump ($FileInfo);
else{
  die ("Load image failed,". $IMG-> Loaderr);
}

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.