Home > Backend Development > PHP Tutorial > Graphics processing with PHP_PHP tutorial

Graphics processing with PHP_PHP tutorial

WBOY
Release: 2016-07-13 10:32:43
Original
784 people have browsed it

Graphics processing

PHP’s graphics processing, the main functions focus on PHP’s graphics processing functions.

You need to master some key points first. What is a picture and how to display it.

The so-called picture is actually a kind of file, but the content is not directly visible to our naked eyes. If we open a picture with Notepad, we will only see garbled characters. In fact, these garbled codes are just garbled codes for me. For a program that can read and write it, it's not messy at all. If we know the format of an image, we can generate one ourselves. Just like the notepad and guestbook we made in the earliest days.

Save some special format data to a file to generate a picture. On the contrary, if we use PHP to directly output this content, the browser will also think that it is a picture.

Let’s confirm this first. Students first prepare a picture. It is recommended that it be smaller and in JPG format. We then use PHP to read this image just like a normal file.

$file = "1.jpg";

$fp = fopen($file, "rb");

$data = fread( $fp, filesize($file));

fclose($fp);

echo $data;

?>

I believe that for students, there is no problem with this code.

Open the file, read the content (all bytes), close the file, and output the content.

Have any students tried it? What will be output after running this code? Take a screenshot to see what it will output.

Maybe some students will be surprised that it is garbled.

Because the browser defaults to thinking that our PHP output is text. Even if it's gibberish, we need to tell the browser that this is a picture. This requires using the header function to send header information and tell the browser that the current output content is in grid format.

Header("Content-type: image/jpeg");

This is the header information used for JPG format images. Content type: image/jpeg. It needs to be added before echo.

$file = "1.jpg";

$fp = fopen($file, "rb");

$data = fread( $fp, filesize($file));

fclose($fp);

Header("Content-type: image/jpeg");

echo $data;

?>

Students, try again.

This code proves one thing: even if the output is garbled, as long as the browser knows what it is, it can be displayed correctly.

In contrast, if we save the read content to another file, we can copy this image.

Here, some students may have some misunderstandings. I think this is still a web page. Students can give it a try. Right-click the blank space of the opened web page and view the source file. You will find that there is no such option. Even if there is, it is gray. This is because this is not a page. The browser already thinks that our PHP program is a picture.

Usually when we use PHP for any form of output, the browser thinks it is an HTML web page and can only see the source code.

If we output image content, to display it correctly, we must tell the browser that this output should not be regarded as a web page, but as a picture. In other words, our php program is a picture. If you want to use this image on other web pages, you need to use the

Treat this PHP program as a picture, rather than writing it directly in this program.

This is wrong, it will only lead to one result.

This is impossible to show.

So, a program that uses PHP to process images must be a single-function PHP program. Unless you don't export the image and just save it.

$file = "1.jpg";

$fp = fopen($file, "rb");

$data = fread( $fp, filesize($file));

fclose($fp);

$fp = fopen("2.jpg", "wb");

fwrite($fp, $data);

fclose($fp);

?>

If the code is written like this, it is another matter, and there is nothing wrong with it. Save the image to another location, and then output HTML to call the image. A PHP program that wants to directly output images must not contain other output and is useless. It can only simply output the content of the picture, which is a bunch of gibberish.

Okay, there is no problem in reading and outputting images.

The content of the file is in a special format that we can’t understand. How to deal with it?

PHP provides specialized graphics processing functions.

The graphics processing function library has a special name called GD library.

This function library does not come with PHP. You need to set loading in php.ini when installing PHP.

The library file name is php_gd2.dll. It is included in the PHP installation package, in the ext directory. If any student's php.ini has not loaded the GD library, please open it now.

In this way, PHP has graphics processing functions available.

The current GD library version that comes with PHP is 2.0.28. PHP 4 comes with gd 2.0, and PHP 3 comes with gd 1.6.

Why do you need to mention this?

Because of the copyright issue of GIF images when gd 2.0 was released. As a free and open source language, PHP cannot provide copyright fees to GIF copyright owners, so it can only suspend support for GIF images. After PHP 5, the copyright of GIF expires, and our PHP will support GIF images again.

Okay, let’s open the PHP manual and take a look at the Image image function.

There are many functions, but they can be roughly divided into four categories: create, draw, set, and output.

If you want to create an image, you can use the imagecreate function. As you can tell from the function name, create an image. From the manual, you can see the syntax format.

Return image resource imagecreate(width, height)

Width and height are in pixels.

There is another function, imagecreatetruecolor, which creates a new true color image and supports more colors.

The function that creates a class will return an image resource, somewhat similar to the return of the fopen function. Resource-type data contains a read-write pointer inside, allowing us to edit pictures.

Let’s try to create an image first, using the imagecreate function.

In order to see this image, we need to export it. But our experience tells us that resource-based content cannot be output directly.

Picture shape function provides us with some functions, namely:

imagejpeg output in JPG format

imagegif Output in GIF format

imagepng Output in PNG format

The function format is the same.

imagejpeg(image resource, [save path])

If you need to save this picture, just write the file name in the second parameter. If you just want direct output, just leave the second parameter unwritten.

Let’s output this image directly now.

Header("Content-type: image/JPEG");

$img =imagecreate(100, 100);

imagejpeg($img);

Create a 100*100 image and export it in JPG format. Remember to tell the browser that this is an image.

What is the result of the operation? Can any of my classmates take a screenshot and take a look?

Yes, a black image will be output. Because we didn't draw anything on it, and we didn't tell it what color it should be.

Let’s do a simpler operation first and paint some color on it. This requires using the imagecolorallocate function.

The function is: assign a color to an image

The function format is

imagecolorallocate(image resource, red, green, blue)

Three primary colors, represented by numbers from 0 to 255. 0 is the darkest and 255 is the brightest. If you need white, all three colors are 255. Black is three colors 0. If you only need red, it is 255 0 0.

header("Content-type: image/jpeg");

$img =imagecreate(100, 100);

imagecolorallocate($img, 255,0,0);

imagejpeg($img);

I’ll just fill it in pure red. Students can try it themselves and set some values ​​for red, green and blue respectively to see the results. This color matching requires some knowledge. Students can also get this color directly in various drawing tools.

The red, green, and blue values ​​in the lower right corner can be used directly. Many software have similar color palettes, making it easy to get various color values.

One thing to note here.

The imagecolorallocate function will fill in the background color of the image only when it is used for the first time. If it is used again, the background color will not be changed.

header("Content-type: image/jpeg");

$img =imagecreate(100, 100);

imagecolorallocate($img, 255,0,0);

imagecolorallocate($img, 0, 0, 255);

imagejpeg($img);

This code does not output the expected blue color. However, this does not mean that the function is useless. The function still works, it's just that the color is not used. We can use this color for other purposes, such as writing.

Let’s try it and write braille on the image.

Among the functions provided by PHP, there are two functions that can be used to write on images, namely imagestring and imagestringup.

imagestring is written horizontally

imagestringup means vertical writing

If I use imagestringup to write it, I have to twist my neck to read it. Okay, let's use imagestring first.

imagestring function prototype

imagestring(image resource, font, start X coordinate, start Y coordinate, word to be written, color)

PHP comes with only 5 fonts, which need to be represented by numbers 1 to 5.

Let’s give it a try.

header("Content-type: image/jpeg");

$img =imagecreate(100, 100);

imagecolorallocate($img, 255,0,0);

$color = imagecolorallocate($img, 0, 0, 255);

imagestring($img, 4, 0,0, 'abcdef', $color);

imagejpeg($img);

Your uncle’s, it’s so dazzling, I’ll change it to a white background to make it better.

Has any student tried to write in Chinese? The results can be disappointing.

Because the font that comes with PHP is extremely weak, it cannot display Chinese characters normally. What to do?

Custom font.

The image function provides us with another function that can use custom fonts to write. Strictly speaking, it is "drawing characters". A font file in bitmap format is required and must support Chinese. The most common font is ttf type. If you have done graphic design, you will be familiar with this. If you have never done it, it doesn’t matter. We can dig out a few of them and use them in our system. The font files that come with the system are in the C:windowsfonts directory. We can find a font that supports Chinese in it. Most of the fonts that come with the WIN system support Chinese. I choose Microsoft Yahei. Back to our PHP.

To use this font file to draw text, you need to use the imagettftext function.

imagettftext function prototype

imagettftext (image resource, font size, font direction, start X coordinate, start Y coordinate, font color, font file, word to be written)

My mother, there are so many parameters. I guess this is the first time for all of you to use a function with so many parameters.

//Create a picture and set a white background

$img =imagecreate(100, 100);

imagecolorallocate($img, 255,255,255);

//Prepare a color,

$color = imagecolorallocate($img, 0, 0, 255);

//Prepare a font file

$font = "msyhbd.ttf";

//Image resources, font size, font direction, start X coordinate, start Y coordinate, font color, font file, word to be written

imagettftext($img, 14, 0, 20, 20, $color, $font, "Chinese support");

//JPG format output image

imagejpeg($img);

For this image file, if the path is not in the current directory, tell PHP where it is.

For example $font = "./font/msyhbd.ttf";

Or $font = "C:\windows\fonts\msyhbd.ttf";

This font file must be found by PHP

imagettftext($img, 14, 180, 150, 150, $color, $font, "Chinese support");

The font direction is 180 degrees, and the result is like this. In addition, Chinese must be utf8 encoded here. This is easy to do, just convert the PHP file to utf8 encoding. Students who use gbk encoding can convert the font encoding.

$text = iconv("gbk", "utf-8", "Chinese support");

As long as there are enough fonts, we can let PHP output any style

$font = "FZKANGFW.TTF";

$text = iconv("gbk", "utf-8", "Chinese support");

imagettftext($img, 20, 0, 150, 150, $color, $font, $text);

This effect can be achieved with the predetermined variable $_SERVER.

$_SERVER['REMOTE_ADDR']

This server variable can get the visitor’s IP address. Various pictures with IP display on the Internet are produced in this way. Isn't it just writing a few words on the picture?

Okay. Then let's learn about it. Draw lines on it.

There are many drawing functions.

imagedashedline - draw a dashed line

imagedestroy - Destroy an image

imageellipse - Draw an ellipse

imagefill - area filling

imagefilledarc - draw an elliptical arc and fill it

imagefilledellipse - draw an ellipse and fill it

imagefilledpolygon - draw a polygon and fill it

imagefilledrectangle - draw a rectangle and fill it

Line drawing is imageline. For other drawing functions, students can refer to the manual by themselves.

Looking at it, the principle is nothing more than: on the image resource, what color to use, which coordinates to start from, and what to draw.

imageline function prototype

(Image data, start X coordinate, start Y coordinate, end X coordinate, end Y coordinate, color)

In mathematics, we know that XY coordinates can determine a point on the plane, and two points can determine a line segment.

//Create a picture and set a white background

$img =imagecreate(300, 300);

imagecolorallocate($img, 200,200,200);

//Prepare a color,

$color = imagecolorallocate($img, 0, 0, 255);

//Draw a line with this color

imageline($img, 0,150, 300,150, $color);

//JPG format output image

imagejpeg($img);

My image is 300*300 size. From 0,150 is the far left, middle position, to the far right, middle position.

If you want to draw a grid, just calculate the coordinates slowly and then draw again.

for($i=0; $i < 6; $i++) {

$y = $i*50;

imageline($img, 0,$y, 300,$y, $color);

}

I won’t say much about vertical lines or anything like that.

There are also various other lines and shapes. Students can practice on their own according to the instructions in the manual.

Many times, our pictures are ready-made. All we have to do is shrink, crop the size.

The pictures are ready-made, we need to load the pictures in. Depending on the different types of pictures, we need different functions to load them.

imagecreatefromjpeg creates an image from a JPG file

imagecreatefromgif GIF

imagecreatefrompng PNG

imagecreatefromwbmp WBMP

imagecreatefromxbm XBM

Whatever function is used to load the image. These functions all belong to the creation class function. Before, we used writing and line drawing functions, which were all painting functions. With this distinction, you won’t feel that there are too many functions. Many functions are actually repeated, just for different types. All operations are directed to the canvas and what is drawn on the canvas.

In fact, PHP cannot shrink an image, it is just a thinking technique. The image copy function imagecopymerge is used.

You can copy part of an image to another image. There is another similar function, imagecopyresampled. They all copy part of an image onto another image. This means that such an operation requires two images. One is the original image and the other is the newly generated image.

The original image can be loaded using the imagefrom series of functions. New pictures, we can create ourselves. Then use the image copy function to copy from the original image to the new image.

If only one area is copied, it is the crop function. If the copy is the entire image size, and the size of the new image is different from the original image, that is, changing the image size, that is, a thumbnail, or enlarging the image.

$image = "1.jpg";

//Read image size

list($width, $height) = getimagesize($image);

//Load images

$bimg = imagecreatefromjpeg($image);

//Create a new image, half the size of the original image

$simg =imagecreatetruecolor($width * 0.5, $height * 0.5);

//On the original image, reduce the entire original image by half and copy it over

imagecopyresampled($simg, $bimg, 0,0, 0,0, $width*0.5, $height*0.5, $width, $height );

//Output small images in JPG format

imagejpeg($simg);

Some students may have discovered that imagecreatetruecolor is used to create new images. True color images instead of imagecreate. Students can try it out and see what the results are when using imagecreate.

Copy the image, I chose the imagecopyresampled function, copy and resize. Similar functions include imagecopyresized.

imagecopyresized

imagecopyresampled

Both functions copy and resize the image. Students can test their differences themselves. Since there are too many parameters, I will make an annotation for you here.

New picture, original picture,

The starting point of the new picture is X, the starting point of the new picture is Y,

Original image starting point X, original image starting point Y,

New image width, new image height,

Original image width, original image height

Just work in groups of two and watch them together.

//Load images

$bimg = imagecreatefromjpeg($image);

//Create a new image, half the size of the original image

$simg =imagecreatetruecolor($width * 0.5, $height * 0.5);

//On the original image, reduce the entire original image by half and copy it over

imagecopyresampled($simg, $bimg, 0,0, $width*0.5, $height*0.5, $width, $height, $width, $height );

This code means

$simg, $bimg, //New picture, original picture

0,0, //Start drawing from 0*0 of the new image

$width*0.5, $height*0.5, //Sampling from the center point of the original image

$width, $height, //The new image and the original image are the same size.

$width, $height //End at the coordinates of the lower right corner of the original image

Since the created image is only half of the original image, this code will make the final image only display the center point of the original image. Contents in the lower right corner. That is, 1/4 of the original image is the so-called cropping.

These functions have too many parameters and are not easy to see. You need to be more careful when calculating each sampling coordinate.

The principle of watermark images is the same. Load two images and create two image objects. Then copy the watermark image to the original image. noodle. In fact, it is just a technique of thinking.

That’s it for graphics functions.

Let me first summarize the main points of this lesson.

1. Be sure to create the image first, load it or create it yourself.

2. You can only draw on images, lines and shapes

3. Text can only be encoded in UTF8, and Chinese fonts are required to display Chinese

4. The image itself cannot be adjusted directly, it can only be adjusted during the copying process.

5. If you want to output images directly, this program cannot output other unnecessary things

6. A program that directly outputs images must be called as a picture.

Image function. Divided into several categories:

Create classes: imagecreate, imagecreatefromjpeg

Setting class: imagecolorallocate, getimagesize

Drawing classes: imagecopyresampled, imageline, imagettftext

Output class: imagejpeg, imagepng

The drawing class has the most functions, and the function formats are also very similar:

At the XX coordinates of the image, draw XX things

The function of copy operation often has as many as 8 coordinates.

The starting point coordinates of the original image, the width and height of the original image, there are four;

The starting point coordinates of the new image, the width and height of the new image, here are four more;

Add the original picture and the new picture. There are about ten parameters.

So, in the general image processing process, after debugging a program, you are often unwilling to go back and change it again. Encapsulate it into a custom function.

For example, thumbnail function.

function size_img($img, $width, $height) {

Just deal with it in the middle.

}

In this way, provide an image and specify the output size to generate a thumbnail. At least it's much easier to use.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/754899.htmlTechArticleGraphics processing PHP graphics processing, the main function is concentrated on PHP graphics processing functions. There are some key points that need to be mastered first. What is a picture and how to display it. The so-called pictures are actually...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template