You get a bonus - 1 coin for daily activity. Now you have 1 coin

GD - working with images on the server side (PHP)

Lecture



Introduction:

PHP capabilities are not limited to creating HTML. PHP can be used to create and manipulate images of various formats, including gif, png, jpg, wbmp, and xpm. In addition, PHP is able to output the image stream directly to the browser. To work, you need PHP compiled with the GD graphics library. GD and PHP may also depend on other libraries, depending on which image formats you will work with.

With the EXIF ​​extension, you can process information stored in JPEG and TIFF image headers. With it, you can access meta tags generated by digital cameras. For the EXIF ​​extension, the GD library is not required.

About installing and configuring the library can be found in the official documentation. Most likely you will not need it because everything is already established for you.


What are we dealing with

I will divide the processing functions with images in PHP into two categories. Those that work with files and those that work with an image in memory (resource).

These functions are quite a lot, and they are all important. I will not describe each of them, the more official documents I don’t do. But we will be able to look at them with examples, and now we will deal with this.

And so, the documentation: http://ru2.php.net/manual/ru/ref.image.php. Yes, yes, you need to click on the link now. Then we go on it.

Our first station will be imagecreatetruecolor .
Documentation says Create a new true color image. I’m sure you also always thought that colors could not be real, and I still think so too =) True color is actually the name, the method of representation and storage of the image, allowing you to display more the number of colors, midtones and shades in RGB format. I’ll remind you that RGB representation from Red Green Blue is a way to express any color with the help of three basic colors.

resource imagecreatetruecolor (int $ width, int $ height)
Our function takes two integer arguments. The length and width of the new image. If you guessed it was spinning down after you opened the documentation, you saw that the result of this function in their example was a small square in black. The fact that the square was black should not scare you at all.
If you want a square of a different color, you will have to try our next function in practice, after one more word about this one.

The result of the function returns the resource data type.
This means that we continue to work directly with something in memory.

Then we will pass this identifier to another function image colorallocate
The function generates color representations in the form used in the picture for further work with this color in the picture.
The very first call to this function sets the image background.

int imagecolorallocate (resource $ image, int $ red, int $ green, int $ blue)
Three parameters are known to us. Numbers from 0 to 255 expressing color in the RGB system.
For black, we need three times 0, for white three times 255.
The first parameter of the resource $ image function is the same identifier that we received earlier in imagecreatetruecolor. This parameter is required in order for the color representation to conform to the requirements of the image format.

And so, created an image, prepared a palette, it's time to start the creative process. Image line
As the name implies, the function draws a line on the image.
We will not go into details about how this happens. We just draw a line.

<?PHP

// create a 100*100 image
$img = imagecreatetruecolor(100, 100);

// allocate some colors
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$blue = imagecolorallocate($img, 0, 0, 255);

// draw some lines
imageline($img, 40, 30, 40, 40, $green);
imageline($img, 50, 30, 50, 40, $green);
imageline($img, 45, 38, 45, 39, $green);

imageline($img, 37, 45, 53, 45, $green);
imageline($img, 37, 43, 37, 45, $green);
imageline($img, 53, 43, 53, 45, $green);

// output image in the browser
header("Content-type: image/png");
imagepng($img);

// free memory
imagedestroy($img);
?>

  GD - working with images on the server side (PHP)

We'll talk about displaying the image in the browser and clearing the memory later, but for now let's see what imageline works with .

bool imageline (resource $ image, int $ x1, int $ y1, int $ x2, int $ y2, int $ color)
What is what you can guess yourself, or spy in the documentation. There is.
I want you not to be afraid to do something wrong. Look in the documentation and go ahead.
I'll tell you once again - if nothing happens, you can always ask a question on the forum =)

The function works with a pointer to an image in memory created by imageCreateTrueColor and a color identifier created by imageColorAllocate. Is it hard? Similarly, most of the functions of working with images work. It accepts a pointer to an image, a color and some specific arguments of its own.

You have time to practice tasks. And then we will look at a couple of key functions for working with images with examples to give you confidence in working with them =)

imagecopyresampled

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)
This feature does a very simple task. Cuts a rectangular slice from one image, changes its size, compresses or expands, stretches or narrows and inserts it into a new image.
This is one of the most dof-argument functions and now you will see that even here everything is very simple.
resource $ dst_image, resource $ src_image - from where and where. Both are pointers to images in memory.
int $ dst_x, int $ dst_y, int $ src_x, int $ src_y - as I said, the function cuts rectangular parts. Here we denote the upper left corner of our rectangles in the original image and the same point in the new image.
int $ dst_w, int $ dst_h, int $ src_w, int $ src_h - the width and height of this rectangle on the new image and the width and height of the rectangle cut from the original image.

And now, in simple words and in Russian:
Take the original image resource $ src_image, cut a rectangle out of it, the left upper corner of which is at the point int $ src_x, int $ src_y and the height and width int $ src_w, int $ src_h. Is that simple?
And now this rectangle with the image is compressed, stretched, narrowed, expanded so that its new length and width correspond to int $ dst_w, int $ dst_h.
Then this new rectangle is wedged into the new image at the point int $ dst_x, int $ dst_y.
You will have the opportunity to try this miracle in action a little closer to completion.

imagecreatefromgif
You will often use this function or its like when working with images. The function is simple as a rake. You give her the name of the file, she gives you a pointer to a picture in memory with which to work.
Pay attention that this createfrom gif . There are also other formats and for them there are already other functions. For example imagecreatefrompng or imagecreatefromjpeg .

Save the processed image using imagegif
The description reads imagegif - Output image to browser or file. In order to roughly understand how this works, we need an editor and a picture. Open the picture with the editor and see a bunch of incomprehensible characters.
Great, this is our picture. This function turns the pixels in our memory into such a record. In order to write all this to a file, specify in the imagegif 2 parameters. The pointer to our image in memory and the name of the file.
imagegif ($ im, 'image.png');

When the browser shows us a picture, it essentially requests the same scribbles from the server and turns them on the screen into an image.
So we can not only save these scribbles to a file, but also immediately send them to the browser. This makes it the same imagegif, but this time without the second parameter.
imagegif ($ im)

But there is one thing. It is necessary to prompt the browser that it should be processed as a picture, and not as plain text. I will remind here about the headings, considered in the chapter "Where php works".
In order to send a header, we use the header function.
the content of the title will be (document type: gif image)
It looks like this: header ("Content-type: image / gif");

Well, finally, the last thing you met here is imagedestroy
It does not delete the $ img variable, but the memory to which the variable indicates it clears. It will be useful if it wants to work with images of a large resolution, for example, with several images in parallel and at the same time not go beyond the limits of the free memory allowed.

Let me remind you that all the memory allocated to the script at runtime is automatically released with the completion of its work.

Well, that's all, we have mastered the theoretical basis ..


Common mistakes:

Fatal error: Call to undefined function ...
This means that you do not have the GD library installed or everything is much simpler - you are sealed in the function name. Installation of GD is described in the documentation. In Denver, it is the default, in ubuntu you may need the command sudo apt-get install php5-gd and restart the server.

Warning: imagecreatefrom .. (a.png) failed to open stream: Permission denied
everything is simple too. Right button in our image and set the right to read all.

The screen displays Resource id # instead of a picture.
= (I already said that the output to the browser is carried out using special functions like imagegif () without the second parameter. And you have somewhere echo $ img; and the screen does not display the contents of the memory, but simply a message that this is a pointer.

Warning: ... (): supplied argument is not a valid Image resource
A pointer was expected, but what you gave to it is a string or something else. And if you are sure that you pass the pointer, but you still get this error, then stop messing around. You are mistaken and better all recheck. Saves a lot of nerves =)

PNG IHDR h6 PIDAT ( JA Mv M4
Yeah, for some reason, the binary code is displayed an image and the browser did not think to make an image of it, but processed it as plain text. Go through the whole lesson again and look for the part in which we sent the image to the browser.


A couple of tasks for mastering the material

I remind once again the stages of programming
1. Statement of the problem
2. Determination of the required operations
3. Selection of suitable functions for each operation (so that's why)
4. Building a chain
5. Debugging with return to the first item.

Remember - you do not get experience now, but learn to recruit it. Think about it when you do tasks.
If you fulfilled them but did not learn anything new for yourself, then either you didn’t fulfill them badly, or you didn’t fulfill them at all. It is unlikely that with another scenario, you would have read to here.

There are also ready-made sets of functions and libraries and services for high-level processing of images, cropping, resizing, building graphs and tables, applying logos, applying filters, searching for faces and objects, and so on.


Challenges

1. Overlay printing
I am sure to add a couple of words in the picture you will not make. Therefore, try to draw a graphic signature. Open the paint and make your autograph. Happened? Fine.
Now we save two photos of Pamela Anderson from Google and add our signature to them.
(Hint: it is probably useful to know that the image has such a parameter as Alpha - denoting transparency. I am sure that Ctrl + F will throw something into your eyes in the list of functions, although this is not at all necessary.)

2. Captcha
We will not do the difficult, we will make simple. Each time, random 4 digits are displayed.
What's the catch? For this we will use a special font - which can be downloaded here. And after our image is white with black text, we apply a negative filter to it and make it appear on the screen in the opposite way, with a black background and white color, and both images are displayed on the screen. (All in one script)

3. php logo
This task is simpler and more authentic - draw a php logo.


1. Overlay printing
I am sure to add a couple of words in the picture you will not make. So try to draw a graphic signature. Open the paint and make your autograph. Happened? Fine.
Now we save two photos of Pamela Anderson from Google and add our signature to them.
(Hint: it is probably useful to know that the image has such a parameter as Alpha - denoting transparency. I am sure that Ctrl F will throw something into your eyes in the list of functions, although this is not at all necessary.)


2. Captcha
We will not do the difficult, we will make simple. Each time, random 4 digits are displayed.
What's the catch? For this we will use a special font.
And after our image is white with black text, we apply a negative filter to it and make it appear on the screen in the opposite way, with a black background and white color, and both images are displayed on the screen. (All in one script)

3. php logo
This task is simpler and longer - draw a php logo


Solutions:

1. Stamp
http://ru2.php.net/manual/ru/ima...es-watermark.php
PHP:

  1. <? PHP
  2. // Load the picture and print
  3. $ stamp = imagecreatefrompng ('stamp.png');
  4. $ im = imagecreatefromjpeg ('photo.jpeg');
  5. // Select the position of our print on the new image. 10 pixels from the left right corner
  6. // what the other two functions do I'm sure you know from the documentation
  7. $ marge_right = 10;
  8. $ marge_bottom = 10;
  9. $ sx = imagesx ($ stamp);
  10. $ sy = imagesy ($ stamp);
  11. // Copy Print To Original Image
  12. // What parameters and their values ​​you will understand by scrolling through the dock. =)
  13. imagecopy ($ im, $ stamp, imagesx ($ im) - $ sx - $ marge_right, imagesy ($ im) - $ sy - $ marge_bottom, 0, 0, imagesx ($ stamp), imagesy ($ stamp));
  14. // Display new image and clear memory
  15. header ('Content-type: image / png');
  16. imagepng ($ im);
  17. imagedestroy ($ im);
  18. ?>





2. captcha

PHP:

  1. <? PHP
  2. if (! isset ($ _ GET ['generate_image']))
  3. {
  4. ?>
  5. <img src = '? generate_image'> <br>
  6. <img src = '? generate_image & inverted'>
  7. <? PHP
  8. die ();
  9. }
  10. $ captcha = rand (1000,9999); // our random four-digit number
  11. $ img = imagecreatetruecolor (88,44);
  12. $ black = imagecolorallocate ($ img, 0, 0, 0);
  13. $ white = imagecolorallocate ($ img, 255,255,255);
  14. imagefill ($ img, 0, 0, $ white);
  15. imagefttext ($ img, 16, 0, 5, 15, $ black, 'arial.ttf', $ captcha);
  16. if (isset ($ _ GET ['inverted'])) imagefilter ($ img, IMG_FILTER_NEGATE);
  17. header ('Content-Type: image / png');
  18. imagepng ($ img);
  19. imagedestroy ($ img);


In case if imagefilter http://ru2.php.net/manual/ru/fun...filter.php#79551 doesn't work for you

3. logo
Well, the easiest option, well, or after sobering up

I will not draw yet, but I will tell the stages.

Create a picture
paint over white
draw an oval
we draw on it a large white text
in the same place with an offset per pixel below and to the right we draw the same text in two sizes smaller, black
Finishes a pair of gray arcs on the left above the oval
and a couple of dark purple to the right.
(It was possible to first draw a dark purple oval, and on it is light to close it
and left only a little srava, instead of drawing an arc.)


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)