PHP-圖片處理

開啓GD擴展(php_gd2.dll)

建立畫布

畫布:一種資源型數據,能夠操做的圖像資源。php

  • 建立新畫布(新建)
    ImageCreate(寬,高);建立基於調色板的畫布。
    imageCreateTrueColor(寬,高);建立真彩色的畫布。
  • 基於圖片建立畫布(打開)
    imageCreateFromJPEG(圖片地址);
    imageCreateFromPNG(圖片地址);
    imageCreateFromGIF(圖片地址);

操做畫布

  • 分配顏色:若是須要在畫布上使用某個顏色,應該先將顏色分配到畫布上。
    顏色標識= imageColorAllocate(畫布,R,G,B)
  • 填充畫布:將填充點,連續而且顏色相同的點進行填充(替換)
    imageFill(畫布, 填充位置x,填充位置Y,顏色標識)
    位置採用座標進行管理:
    畫布的原點(左上角):0, 0
    畫布的右下角:width-1,height-1

輸出畫布

輸出到圖片文件或直接輸出(直接輸出到瀏覽器)數組

  1. imagePNG(畫布[, 文件地址]);
  2. imageJPEG();
  3. imageGIF();

注意:
若是沒有第二個參數,表示直接輸出。
若是直接輸出到瀏覽器,須要告知瀏覽器響應數據的類型應該是XXX格式的圖片:header(Content-Type: image/XXX)
一個畫布能夠輸出屢次,輸出爲各類格式瀏覽器

銷燬畫布資源

imageDestroy();框架

例:驗證碼生成(修改了一下CI框架的)

<?php
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = ''){
  $defaults = array(
    'word'    => '',
    'img_path'  => '',
    'img_url' => '',
    'img_width' => '150',
    'img_height'  => '30',
    'font_path' => '',
    'expiration'  => 7200,
    'word_length' => 4,
    'font_size' => 16,
    'img_id'  => '',
    'pool'    => '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ',
    'colors'  => array(
      'background'  => array(255,255,255),
      'border'  => array(153,102,102),
      'text'    => array(204,153,153),
      'grid'    => array(255,182,182)
    )
  );

  // -----------------------------------
  // 遍歷defaults將每一個下標建立出變量
  // 若是參數$data中有這個下標則使用$date中的值做爲該變量的值
  // -----------------------------------
  foreach ($defaults as $key => $val){
    if ( ! is_array($data) && empty($$key))
    {
      $$key = $val;
    }
    else
    {
      $$key = isset($data[$key]) ? $data[$key] : $val;
    }
  }
  // -----------------------------------
  // 檢測gd擴展是否加載
  // -----------------------------------
  if (! extension_loaded('gd')){
    return FALSE;
  }
  
  // -----------------------------------
  // Do we have a "word" yet?
  // -----------------------------------
  if (empty($word))
  {
    $word = '';
    $pool_length = strlen($pool);
    $rand_max = $pool_length - 1;

    // PHP7 or a suitable polyfill
    if (function_exists('random_int'))
    {
      try
      {
        for ($i = 0; $i < $word_length; $i++)
        {
          $word .= $pool[random_int(0, $rand_max)];
        }
      }
      catch (Exception $e)
      {
        // This means fallback to the next possible
        // alternative to random_int()
        $word = '';
      }
    }
  }

  if (empty($word))
  {
    for ($i = 0; $i < $word_length; $i++)
    {
      $word .= $pool[mt_rand(0, $rand_max)];
    }
  }
  elseif ( ! is_string($word))
  {
    $word = (string) $word;
  }

  // -----------------------------------
  // Determine angle and position(angle畫字的時候用,x_axis和y_axis畫圓的時候用)
  // -----------------------------------
  $length = strlen($word);
  $angle  = ($length >= 6) ? mt_rand(-($length-6), ($length-6)) : 0;
  $x_axis = mt_rand(6, (360/$length)-16);
  $y_axis = ($angle >= 0) ? mt_rand($img_height, $img_width) : mt_rand(6, $img_height);

  // Create image
  // PHP.net recommends imagecreatetruecolor(), but it isn't always available
  $im = function_exists('imagecreatetruecolor')
    ? imagecreatetruecolor($img_width, $img_height)
    : imagecreate($img_width, $img_height);

  // -----------------------------------
  //  Assign colors
  // ----------------------------------

  is_array($colors) OR $colors = $defaults['colors'];

  foreach (array_keys($defaults['colors']) as $key)
  {
    // Check for a possible missing value
    is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key];
    /*
    *'background','border','text'這三個顏色給畫布,並放到$colors[$key]數組中。
    *處理前$colors爲
    *array (size=4)
    *  'background' => 
    *    array (size=3)
    *      0 => int 255
    *      1 => int 255
    *      2 => int 255
    *  'border' => 
    *    array (size=3)
    *      0 => int 153
    *      1 => int 102
    *      2 => int 102
    *  'text' => 
    *    array (size=3)
    *      0 => int 204
    *      1 => int 153
    *      2 => int 153
    *  'grid' => 
    *    array (size=3)
    *      0 => int 255
    *      1 => int 182
    *      2 => int 182
    *處理後$colors爲
    *array (size=4)
    *  'background' => int 16777215
    *  'border' => int 10053222
    *  'text' => int 13408665
    *  'grid' => int 16758454
    */
    $colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]);
  }
  // Create the rectangle
  ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']);

  // -----------------------------------
  //  Create the spiral pattern(建立旋轉圖樣)
  // -----------------------------------
  //theta:n. 希臘字母的第八字;時間遞耗值
  $theta    = 1;
  $thetac   = 7;
  //radius:半徑
  $radius   = 16;
  //circles:圓
  $circles  = 20;
  //points:點
  $points   = 32;
  /*這裏沒弄懂*/
  for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++)
  {
    $theta += $thetac;
    $rad = $radius * ($i / $points);
    $x = ($rad * cos($theta)) + $x_axis;
    $y = ($rad * sin($theta)) + $y_axis;
    $theta += $thetac;
    $rad1 = $radius * (($i + 1) / $points);
    $x1 = ($rad1 * cos($theta)) + $x_axis;
    $y1 = ($rad1 * sin($theta)) + $y_axis;
    imageline($im, $x, $y, $x1, $y1, $colors['grid']);
    $theta -= $thetac;
  }

  
  // -----------------------------------
  //  Write the text(有字體和沒字體分兩種處理)
  // -----------------------------------

  $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext'));
  if ($use_font === FALSE)
  {
    ($font_size > 5) && $font_size = 5;
    $x = mt_rand(0, $img_width / ($length / 3));
    $y = 0;
  }
  else
  {
    ($font_size > 30) && $font_size = 30;
    $x = mt_rand(0, $img_width / ($length / 1.5));
    $y = $font_size + 2;
  }

  for ($i = 0; $i < $length; $i++)
  {
    if ($use_font === FALSE)
    {
      $y = mt_rand(0 , $img_height / 2);
      imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']);
      $x += ($font_size * 2);
    }
    else
    {
      $y = mt_rand($img_height / 2, $img_height - 3);
      imagettftext($im, $font_size, $angle, $x, $y, $colors['text'], $font_path, $word[$i]);
      $x += $font_size;
    }
  }
  // Create the border
  imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']);

  // -----------------------------------
  //  Generate the image(生成圖像)
  // -----------------------------------

  if (function_exists('imagejpeg'))
  {
    header('Content-Type:image/jpeg');
    imagejpeg($im);
  }
  elseif (function_exists('imagepng'))
  {
    header('Content-Type:image/png');
    imagepng($im);
  }
  else
  {
    return FALSE;
  }

  ImageDestroy($im);

  return array('word' => $word);
}

create_captcha();

驗證碼刷新:dom

onclick="this.src = 'url?...&'+Math.random()"
相關文章
相關標籤/搜索