Image Processing
Website development needs often deal with images, such as thumbnails of course, the user avatar, etc., using PHP to process images very simple.
Configuration Environment
PHP GD image processing needed to support the library.
Modify the php.ini file in the windows system, remove the front of extension = php_gd2.dll ;
open image processing support.
centos use yum install php-gd*
ubuntu system use apt-get install php7.3-gd
Detection GD library is loaded
$has = extension_loaded('GD');
var_dump($has);
Instructions
PHP create images step
- Send HTTP header information, the image contents of the statement
- Creating the Canvas
- Create a color drawing needed
- Drawing (filled canvas, circle, square painting, painting lines, writing the canvas)
- Output image
- Canvas release resources
Header
By header () function tells the browser, the output is an image instead of text or HTML, so the browser can display the image properly.
- header('Content-type:image/gif');
- header('Content-type:image/jpeg');
- header('Content-type:image/png');
header('Content-type:image/jpeg');
readfile('user.jpeg');
Creating the Canvas
imageCreateTrueColor(width,height)
- Two parameters are passed canvas width and height, width and height exceeding portion will not be displayed at the time of drawing, and this size is the size when the generated image file.
- The return value is the resource type.
Set Color
imageColorAllocate(img_resource,R,G,B)
- Belonging to a color image resources exist.
- Color is actually an integer value.
- Scope of the following three parameters for an incoming color value of from 0 to 255
Fill Color
imageFill(img_resource,x,y,color)
- (X, y) represents the start point from which the fill color coordinates
- Do not fill the canvas, the default is black
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
imagefill($res, 0, 0, $red);
imagejpeg($res);
Draw a rectangle
Draw hollow rectangle
- imageRectangle(img_res,x1,y1,x2,y2,color)
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imagerectangle($res, 100, 100, 200, 200, $green);
imagejpeg($res);
Filled rectangle drawing the filled
imageFilledRectangle (img_res,x1,y1,x2,y2,color)
- (X1, y1) to the upper left corner coordinates, (x2, y2) for the lower right corner coordinates
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(1000, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imagefilledrectangle($res, 100, 100, 300, 300, $green);
imagejpeg($res);
Draw a circle
Hollow round draw
- imageEllipse(img_res,x,y,w,h,color)
Filled with good solid round draw
- imageFilledEllipse(img_res,x,y,w,h,color)
Description:
- (X, y) coordinates as the center. w is the width, h is the height
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(500, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imageellipse($res, 250, 250, 100, 100, $green);
imagejpeg($res);
Drawing lines
imageLine(img_res,x1,y1,x2,y2,color)
- (X1, y1) as the starting point coordinates
- (X2, y2) is the coordinates of the end point
$res = imagecreatetruecolor(500, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
imageline($res, 0, 0, 499, 499, $green);
imagepng($res);
Drawing pixels
bool imagesetpixel ( resource $image , int $x , int $y , int $color )
- (X1, y1) to coordinates
header('Content-type:image/jpeg');
$res = imagecreatetruecolor(500, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
for ($i = 0; $i < 600; $i++) {
imagesetpixel($res, mt_rand(0, 500), mt_rand(0, 500), $green);
}
imagepng($res);
Output image
Output images in different formats in different ways:
- imagegif(img_resource[,filename])
- imagejpeg(img_resource[,filename])
- imagepng(img_resource[,filename])
- imagebmp(img_resource[,filename])
- It indicates the file when storing a second parameter, if the same name exists overwrite
Release image
imageDestroy(img_resource)
- The image output is completed timely release of resources, the more memory space for program needs.
Enter the text
array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
- Parameters: image resource, the font size, the angle, the basic point of the first character (roughly the lower left corner of the character), Y coordinate (position of the fonts baseline), color, font files, text strings (UTF-8 coding)
header('Content-type:image/png');
$res = imagecreatetruecolor(500, 500);
$red = imagecolorallocate($res, 255, 0, 0);
$green = imagecolorallocate($res, 0, 255, 0);
imagefill($res, 0, 0, $red);
$font = realpath('source.otf');
imagettftext($res, 50, 0, 0, 50, $green, $font, 'houdunren.com');
imagepng($res);
imagedestroy($res);
array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
- Range of size of the text box, can easily control the position of text output
- It returns an array containing 8 units representing four frame of text:
variable | position |
---|---|
0 | The lower left corner X position |
1 | Y position of the lower left corner |
2 | The bottom right X position |
3 | Y position of the lower right corner |
4 | The upper right corner X position |
5 | The upper right corner Y position |
6 | X position of the upper left corner |
7 | Y position of the upper left corner |
In the upper right corner of the canvas text display
$font = realpath('source.otf');
$text = 'houdunren.com';
$size = 16;
$box = imagettfbbox($size, 0, $font, 'houdunren.com');
$width = $box[2] - $box[0];
$height = $box[0] - $box[7];
imagettftext($res, $size, 0, 500 - $width, $height, $green, $font, 'houdunren.com');
Text displayed in the middle of the canvas
...
imagettftext($res, $size, 0, 250 - $width / 2, 250 - $height / 2, $green, $font, 'houdunren.com');
...
External image
Open the image file
- imageCreateFromgif(filename/url)
- imageCreateFromjpeg(filename/url)
- imageCreateFrompng(filename/url)
- imageCreateFrombmp(filename/url)
- Returns a resource type
get information
imagesx (img_resource)
- Get image width
imagesy (img_resource)
- Get image height
getimagesize(img_file)
- array getimagesize ( string $filename [, array &$imageinfo ] )
Copy image
Part of a copied image
- bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
Copy and merge part image
- 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 )
Picture zoom
Copy partial image and resize
- bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
Verification code
Instructions
# 后台code.php
include 'Captcha.php';
$code = new Captcha(100, 30, 20);
$code->make();
# 前台
<img src="code.php" alt="">
Class codes
<?php
class Captcha
{
protected $width;
protected $height;
protected $res;
protected $len = 4;
protected $font;
protected $size;
public function __construct(int $width = 100, int $height = 30, $size = 20)
{
$this->width = $width;
$this->height = $height;
$this->font = realpath('source.otf');
$this->size = $size;
}
public function make()
{
$res = imagecreatetruecolor($this->width, $this->height);
imagefill($this->res = $res, 0, 0, imagecolorallocate($res, 200, 200, 200));
$this->text();
$this->line();
$this->pix();
$this->render();
}
protected function text()
{
$text = 'abcdefghigk123456789';
for ($i = 0; $i < $this->len; $i++) {
$x = $this->width / $this->len * $i;
$box = imagettfbbox($this->size, 0, $this->font, $text[$i]);
imagettftext(
$this->res,
$this->size,
mt_rand(-20, 20),
$x,
$this->height / 2 + ($box[0] - $box[7]) / 2,
$this->textColor(),
$this->font,
strtoupper($text[$i])
);
}
}
protected function pix()
{
for ($i = 0; $i < 300; $i++) {
imagesetpixel(
$this->res,
mt_rand(0, $this->width),
mt_rand(0, $this->height),
$this->color()
);
}
}
protected function line()
{
for ($i = 0; $i < 6; $i++) {
imagesetthickness($this->res, mt_rand(1, 3));
imageline(
$this->res,
mt_rand(0, $this->width),
mt_rand(0, $this->height),
mt_rand(0, $this->width),
mt_rand(0, $this->height),
$this->color()
);
}
}
protected function color()
{
return imagecolorallocate($this->res, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));
}
protected function textColor()
{
return imagecolorallocate($this->res, mt_rand(50, 150), mt_rand(50, 150), mt_rand(50, 150));
}
protected function render()
{
header('Content-type:image/png');
imagepng($this->res);
}
}
Watermark class
Called
<?php
include "Water.php";
$water = new Water("logo.png");
$water->make('sun.png', '2.png', 5);
Watermark source category
<?php
class Water
{
//水印资源
protected $water;
//水印图片
public function __construct(string $water)
{
$this->water = $water;
}
//入口方法
public function make(string $image, string $filename = null, int $pos = 9)
{
$res = $this->resource($image);
$water = $this->resource($this->water);
$postion = $this->position($res, $water, $pos);
imagecopy($res, $water, $postion['x'], $postion['y'], 0, 0, imagesx($water), imagesy($water));
$this->showAction($image)($res, $filename ?: $image);
}
//获取资源对象
protected function resource($image)
{
$info = getimagesize($image);
$function = [1 => 'imagecreatefromgif', 2 => 'imagecreatefromjpeg', 3 => 'imagecreatefrompng'];
$call = $function[$info[2]];
return $call($image);
}
//根据类型输出图片
protected function showAction(string $image)
{
$info = getimagesize($image);
$function = [1 => 'imagegif', 2 => 'imagejpeg', 3 => 'imagepng'];
return $function[$info[2]];
}
//位置
protected function position($des, $res, int $pos)
{
$info = ['x' => 0, 'y' => 0];
switch ($pos) {
case 1:
break;
case 2:
$info['x'] = (imagesx($des) - imagesx($res)) / 2;
break;
case 3:
$info['x'] = (imagesx($des) - imagesx($res));
break;
case 4:
$info['y'] = (imagesy($des) - imagesy($res)) / 2;
break;
case 5:
$info['x'] = (imagesx($des) - imagesx($res)) / 2;
$info['y'] = (imagesy($des) - imagesy($res)) / 2;
break;
}
return $info;
}
}
Thumbnails
Called
include 'Resize.php';
$image = new Resize;
$image->make('sun.png', '1.jpeg', 200, 200, 3);
Thumbnails source category
<?php
class Resize
{
public function make(string $file, string $to = null, int $width = 200, int $height = 200, int $type = 3)
{
$image = $this->resource($file);
$info = $this->size($width, $height, imagesx($image), imagesy($image), $type);
$res = imagecreatetruecolor($info[0], $info[1]);
imagecopyresampled($res, $image, 0, 0, 0, 0, $info[0], $info[1], $info[2], $info[3]);
header('Content-type:image/jpeg');
imagejpeg($res);
}
protected function size($rw, $rh, $iw, $ih, int $type)
{
switch ($type) {
case 1:
//固定宽度,高度自动
$rh = $rw / $iw * $ih;
break;
case 2:
//高度固定,宽度自动
$rw = $rh / $ih * $iw;
break;
case 3:
//固定宽度,高度裁切
$ih = $iw / $rw * $rh;
break;
default:
if (($iw / $rw) > ($ih / $rh)) {
$iw = $ih / $rh * $rh;
} else {
$ih = $iw / $rw * $rw;
}
}
return [$rw, $rh, $iw, $ih];
}
protected function resource(string $image)
{
if (!file_exists($image) || getimagesize($image) === false) {
throw new Exception("file dont exists or it's not an image file");
}
$functions = [1 => 'imagecreatefromgif', 2 => 'imagecreatefromjpeg', 3 => 'imagecreatefrompng'];
$info = getimagesize($image);
$call = $functions[$info[2]];
return $call($image);
}
}