the Internet Windows Android

PHP features working with images. Full Image Load Guide to PHP

The article describes how to work with the PHP - GDLIB extension, which allows you to dynamically form images on Web pages.
Author - NYKOH (NIKO)
Translation from French - Anton Fedorchenko
Original address - http://www.phpdebutant.org/article111.php

To understand this article, it is necessary to have an idea of \u200b\u200bthe elementary basics of PHP, as well as working with images.

Translator note

in the examples, all identifier names are given in French. In order to facilitate the reader's understanding of the code, we offer their translation:
blanc - White
bleu - Blue
couleur - color
couleur_Fond - Background Color
fichier - File
gRIS - Gray
hauteur - height
hauteurimage - image height
largeur - Width
largeurimage - image width
mois - Month
noir - black
police - Font Headset
rouge - Red
tableau - array
vert - Green

Translator note

By default, in PHP 5, all extensions are disabled, including an extension to form dynamic images - GD. For instructions for setting this expansion, you should contact an article.

Goal: To teach the use of various functions of the GD library, designed for dynamic image creation.

The GD library is a set of features to work with images. Thanks to her, it is possible not only to dynamically create your own images, but also to receive various information about them, change the size, etc.

Attention: Before you start work, you need to know something. The fact is that there are several different versions of this PHP extension, and hosting service providers can disable certain functions, and even the entire GD library. For what purpose? It is known that image processing is a large load on the server.

So, you need to know the version of the GD library installed on the hosting you use, as well as get information about the allowed functions. The first thing to be done is to use the PHPInfo function. Perform the following script:

phpinfo.php.

phpinfo ();
?>

If you have a table similar to this - everything is fine (especially if the library version is newer than 2.0)

GD.

GD Support

GD VERSion.

Freetype Support

Freetype Linkage.

JPG Support

PNG Support

WBMP Support

As mentioned above, some possibilities can be disabled. In this case, you should simply try to use one function. If this leads to an error: Fatal Error: Call to Undefined Function, - You should not have any doubt that this function is disabled.

I) creation of canvas

First you need to create empty canvas. Immediately explain that in this article we will tell solely on images in PNG or JPG format, GIF format will remain without our attention. The fact is that this format has ceased to be supported by the GD library, starting with version 1.3, though limited support for GIF appeared again in version 2. Conclusion: PNG format is a profitable alternative to GIF

Important note

In all training courses of the site www.phpdebutant.org, the scripts were targeting the dynamic creation of HTML pages. This time, using the GD library, we create images, so in this case you must forget during the design of Echo and Print. By default, the PHP script generates an HTML page that does not require clarification in the form of sending a special HTTP-core. But if we create an image, at the very beginning of the script, you must specify its type, sending the corresponding header, for example for PNG: Header ("Content-Type: Image / PNG");

Further actions are reminded something with a graphic editor. You create a new image, specifying dimensions, select the background color and save it in the desired format. This sequence of actions illustrates the following script:

imagevide.php.

Header ("Content-Type: Image / PNG");
$ im \u003d imagecreate (200, 100)
or DIE ();
$ couleur_fond \u003d imagecolorallocate ($ im, 255, 0, 0);
Imagepng ($ im);
?>

This small script generates a red rectangle (very modest, but good start). Description of the mechanism:

  • The ImageCreate function returns the $ IM descriptor. The $ IM descriptor must be transmitted to all image drawing functions. The ImageCreate function parameters correspond to the length and width of the image being created (200x100).
  • Operator's task OR DIE - interception of possible errors.
  • Create color can be created using the ImageColorallocate function. It is used for
    • creation of color and its preservation in a variable in order to subsequent use
    • add color to $ im image palette

Its parameters correspond to the red, green and blue components of the color and represent integers from 0 to 255. In this example, we created a red color.

Important note

this color corresponds to the background color, since it is first added to the image palette.

Calling an imagevide.php script (empty_ .PHP) will create an image in PNG format. In order to use it on the Web site, you need to act as well as in the case of "classic" images.

Quite easy! You can even transmit the parameters of the script that will generate an image (for example, the background color).

So you already have some basic knowledge in order to start drawing. If you want to deepen them - here are some interesting features

  • You can replace imagecreate on ImageCreateTusolor to create a 32-bit image (perfect for photos)
  • You can replace imagepng function imagejpeg To create an image in JPEG format (do not forget to change the HEADER function parameter on the Header ("Content-Type: Image / JPEG").
  • Below we will see that the generated image can be saved

Ii) image drawing functions

First you need to know that any drawing is associated with the concept of coordinates, so in this small paragraph of the article we will give some ideas about this issue.
The upper left corner of the image has coordinates (x \u003d 0, y \u003d 0), and the lower right (x \u003d image width, y \u003d image height).

For example, for an image with a resolution of 100 per 200 pixels, the coordinates will be:

Different features of the image drawing are taken as the parameters of its coordinate. Get to pass them in the desired order. For example, in order to draw a rectangle, it is necessary to transfer the coordinates of two points of the corresponding function (imageRectangle). The coordinates of the first point correspond to the upper left corner of the image, the coordinates of the second point correspond to the lower right corner. Do not confuse arguments because some functions can issue erroneous results.


Here is a list of functions that are necessary for drawing various shapes, as well as for placing text on the created image.
For each function you will find a brief description of the syntax and destination.
We do not aim to bring an example of using for each function, here you will find only a brief description. The table also specifies the version of the library, starting with which one or another function is supported. Examples of use of some functions can be found in the section of the official manual dedicated to

Syntax example

Description

Creates an empty canvas (256 colors) $ IM $ Largeur height and $ HAUTEUR width. (PNG format is preferred)

This feature is similar to ImageCreate But the depth of the color of the image is not limited to 256 colors. (JPEG format is preferred)

It places in the variable $ COL color components of which are $ ROUGE, $ vert, $ bleu (range 0 .. 255). For details, see in the first part.

Creates an ellipse on an image of $ im with a center at a point ($ x, $ y), $ l wide, $ H high and $ col color.

Identical Imagellipse, but the ellipse is filled with $ col

Creates a $ COL color rectangle on an image, located between a point with coordinates ($ x, $ Y) and the lower right angle of the color $ col

Draws a line color $ col, which passes between two points with coordinates ($ x1, $ Y1) and ($ x2, $ Y2)

The image of $ IM paints a polygon whose coordinates are listed in the $ Points array ($ Points \u003d $ x0, $ POINTS \u003d $ Y0, $ Points \u003d $ x1, $ Points \u003d $ y1, etc.), $ num_points - quantity Points in an array, $ col - color.

Identical ImagePolygo, but the ellipse is filled with $ col

The image $ IM draws a rectangle, the upper left corner of which has coordinates ($ x0, $ Y0), and the lower lower ($ x1, $ y1). $ col - rectangle color

Identical imageRectangle, but the ellipse is filled with $ col

These functions allow you to change the style of the static lines. For more information, see the official documentation, especially pay attention to the use of the ImageSetStyle function, which is also indicative for ImageSetbrush function.

In the image $ IM paints a point with coordinates ($ x, $ Y) and $ col

Changes the thickness of lines created by various functions.

In an image, $ IM creates a line $ chaine with coordinates (left top corner) ($ x, $ y) $ Col $ Police colors - size (headset) font (from 0 to 5)

Identical imagestring, but the string is displayed vertically

Iii) example is the first: site visits statistics in the form of a graph

To apply the knowledge gained in practice - create a simple script example. Often it is necessary to present the statistics of the site visits in the form of a histogram

We assume that you have already developed the part of the script that is responsible for accounting for visitors (possibly using the MYSQL table). We will not talk about her implementation here, this is not the purpose of this article. Suppose that visiting statistics for each month is placed in an array of $ visites. In this article, we fill the array "manually", but you can do it yourself using the data of your MYSQL table.

a) Visiting statistics: Creating an image and color

Let's start with the creation of an array that contains the statistics of the site visits for 12 months (12 elements). Then we will generate a picture with a resolution of 400x300 and create three colors, one of which (white) will be the color of the background.

visites.php.

$ Visites \u003d Array (138, 254, 381, 652, 896, 720, 140, 556, 663, 331, 407, 768);

Header ("Content-Type: Image / PNG");
$ largeurimage \u003d 400;
$ hauteurimage \u003d 300;
$ im \u003d imagecreate ($ LargeurImage, $ Hauteurimage)
OR DIE ( "Error when creating an image");

$ noir \u003d imagecolorallocate ($ im, 0, 0, 0);
$ bleu \u003d imagecolorallocate ($ im, 0, 0, 255);
?>

b) draw the axis of the graph

Position the horizontal axis of time (simple black line) into the lower part of the image, leaving the field in 10 pixels.

At the bottom, we sign the number of each of the 12 months using the FOR cycle and the ImageString function. Numbers are located every 30 pixels, starting on the left side of the image.

Finally, we spend the vertical line, the axis of the ordinate statistics of visits.

// hold a horizontal line, the axis of the abscissa (time)
ImageLine ($ im, 10, $ HauteurImage-10, $ LargeurImage-10, $ HauteurImage-10, $ noir);
// withdraw the sequence number of each of 12 months
for ($ mois \u003d 1; $ mois imagestring ($ im, 0, $ Mois * 30, $ HauteurImage-10, $ MOIS, $ noir);
}

// We carry out a vertical line to the axis of the ordinate (number of visits)
Imageline ($ im, 10, 10, 10, $ hauteuriage-10, $ noir);
?>

c) draw sticks

Now go to a more complex task - drawing sticks.

First, we need to find out the maximum number of visitors we will present on the schedule. Here we have chosen a random value - 1000, but in fact, you will probably have to calculate it, carrying out a request for the maximum value of the column of your MYSQL table. We will make it easier ...

For each month, it is necessary to calculate the height of the created rectangle. To do this, it is necessary to solve the equation, knowing that the height of the rectangle (sticks) for the maximum number of visits will be equal to the height of the entire image. Based on the number of visits for a certain month, we get the desired height

It remains only to draw every rectangle, starting with the coordinates of its upper left corner and ending with the bottom right.

Add the number of visits for a month over each rectangle to improve the histogram.

// Maximum visits
$ visitesmax \u003d 1000;

// Draw a stick
for ($ mois \u003d 1; $ mois<= 12 ; $mois ++) {
$ HauteurimageRectangle \u003d Round (($ Visites [$ MOIS - 1] * $ HauteurImage) / $ Visitesmax);
ImageFilledRectangle ($ im, $ Mois * 30 - 7, $ Hauteurimage - $ HauteurimageRectangle, $ Mois * 30 + 7, $ HauteurImage - 10, $ Bleu);
Imagestring ($ im, 0, $ MOIS * 30 - 7, $ Hauteurimage - $ HauteurImageRectangle - 10, $ Visites [$ MOIS - 1], $ noir);
}

// that's all
Imagepng ($ im);
?>

d) And here is the result!

The result, of course, do not call excellent, but it should be borne in mind that we managed to do something more or less presentable by writing only 20 lines of a simple code, which in itself is not bad.

Histogram of attendance for 12 months.


IV) Other useful features

Here is another set of useful features designed to manage the color palette, as well as for obtaining different image information.

Description

"This feature uses the name of the $ Fichier file as a parameter and returns an array containing 4 elements: (1) $ tableau image width (PX), (2) $ Tableau Height of the image (PX), (3) $ Tableau image type (cm . Documentation), (4) $ Tableau Returns a string that can be inserted into the IMG tag (width \u003d "" 1024 "" Height \u003d "" 768 ")"

An image area of \u200b\u200b$ IM, the $ COL color becomes transparent. To save transparency, use PNG format

Copy the rectangular image area $ src_im on the image $ dst_im. The copy area is limited to the coordinates of the point of the upper left angle ($ src_x, $ src_y), $ src_l width and $ src_h height. The copied area appears in the recipient image at the point with coordinates. ($ DST_X, $ DST_Y)

Identical imagecopy, in addition to this, the function performs a gradual transition of the tones of the $ intensite intensity, which takes values \u200b\u200bfrom 1 to 100.

Performs the same effect as imagecopy, and also makes a change in image size. See the following example

Identical imagecopyresampled, but the result of scaling is less ruling, but the function works faster.

Returns the resource identifier, $ im, indicating the image that is in the JPEG $ Fichier format file.

Returns the resource identifier, $ im, indicating an image that is located in the PNG $ Fichier PNG format.

Returns the width of the image $ im

Returns the height of the $ im

V) Example Second: Miniature Generation (Reduced Copy Images)

This example is intended to create a reduced copy of an existing image. You may have to implement this feature when writing a photo gallery on PNP, in which the photos are presented in the form of a miniature, and the visitor can click on them with the mouse to enlarge. In this example, we will generate a miniature equipped with a frame and some explanations (size and image name)

a) Beginning

Unlike the first example, this script will record an image into a file, and not generate it on the fly. Therefore, the need to send a special HTTP header using the Header () function disappears. Thus, the script becomes "classic" and can generate HTML.

Let's start with the creation of an empty canvas with a size of 200x150, then consider the existing image (from the file) using the ImageCreateFromJPEG function. Then we may also need the size of the source image, for this we will use the ImageSX and Images.

miniature.php.

$ fichierce \u003d "photo3.jpg";

$ LargeURDestination \u003d 200;
$ hauteurdestination \u003d 150;
$ im \u003d imageCreaCeeColor ($ LargeURDestination, $ HauteURDestination)
OR DIE ( "Error when creating an image");

$ Source \u003d ImageCreateFromJPEG ($ Fichierce);

$ largeursource \u003d imagesx ($ Source);
$ hauteursource \u003d imagesy ($ source);
?>

b) Frame

After creating several colors, draw the frame. To simplify the task, we will use various shades of gray.

There is a simple way to create a similar frame that lies in the drawing of several multi-colored rectangles embedded one in another. We start from the biggest rectangle of the dark color (its size coincides with the size of the image). Then we impose another smaller rectangle in size, the color of which will be lighter, etc.

The thickness of the frame created by us is 8 pixels.

$ blanc \u003d imagecolorallocate ($ im, 255, 255, 255);
$ GRIS [0] \u003d ImageColorallocate ($ im, 90, 90, 90);
$ GRIS [1] \u003d imageColorallocate ($ im, 110, 110, 110);
$ GRIS [2] \u003d imagecolorallocate ($ im, 130, 130, 130);
$ GRIS [3] \u003d imageColorallocate ($ im, 150, 150, 150);
$ GRIS [4] \u003d imagecolorallocate ($ im, 170, 170, 170);
$ GRIS [5] \u003d ImageColorallocate ($ im, 190, 190, 190);
$ GRIS [6] \u003d imageColorallocate ($ im, 210, 210, 210);
$ GRIS [7] \u003d imagecolorallocate ($ im, 230, 230, 230);

For ($ i \u003d 0; $ i<= 7 ; $i ++) {
ImageFilledRectangle ($ IM, $ I, $ I, $ LargeURDestination - $ I, $ HauteURDestination - $ I, $ GRIS [$ i]);
}
?>

c) Creating miniatures

For the creation of thumbnails, the ImageCopyresampled feature is used. It copies one image to another, it can change the size of the copied area. This function takes several parameters whose value is obvious. We list them in order:

  • ($ im) Image Recipient
  • ($ Source) Image-source
  • The coordinate of the image of the recipient image to which the image is superimposed.
  • Coordinate Y.
  • Coordinate X Copy Source Image Area (0 If we want to copy the entire image)
  • Coordinate (Y)
  • The width of the copy, which is inserted into the source image ($ largeurdestination- (2 * 8) the width of the recipient image minus the frame width on the right and left).
  • Copy height (We do the same operations as with a width)
  • Width of the Copy Source Image Area
  • , $ hauteursource);
    Imagestring ($ im, 0, 12, $ HauteURDestination - 18, "$ Fichierce - ($ Largeursource X $ Hauteursource)", $ blanc);
    ?>

    d) Saving the result.

    We can only save the result in the file, whose name begins with mini_. This we will do with the imagejpeg function.
    When this feature has only one parameter, the image is displayed in the user's browser. However, if the file name is passed as the second parameter, it will not happen to the browser, and the picture will be saved in the specified file. The same rule is valid for the function imagepng

    My image is not displayed, the browser behaves as if it does not exist.
    Most likely, the error should be signed in your script. Make a comment from the header string ("Content-Type: Image / PNG") (or Header ("Content-Type: Image / JPEG")), as well as from the ImagePNG string ($ im) (orimagejpeg ($ im)) to Get an error message

    Script is long done on my hosting, is it normal?
    If you use "heavy" functions as imagecopyresampled, it is not surprising. The PHP interpreter, installed on the hosting, and without this work there is enough ...

    The colors of my image are distorted (or it is displayed as black and white), why?
    Most likely you used the ImageCreate feature, which limits the color palette of 256 colors. To overcome this restriction, use the ImageCreateTusolor function instead of ImageCreate.

    Finishing this article, we show the result that can be obtained by combining two examples of this article. Here, we added halftone to the histogram using the same method as in Example 2.

    Result


In this article, we will describe in detail the mechanism for loading images to the server using PHP without resorting to third-party components and frameworks. We will learn to safely load images not only from the local user machine, but also remote files by reference. All examples of the code I will write in a procedural style, in order to read the code faster, and not jump from one method to another. Manual fully copyright and does not claim any academicity of presentation.

§one. General principles

The entire sequence of image loading to the server can be displayed as follows: setting up php.inifile Gettingsecurity checkdata validationsaving on disk. The process of loading a picture from a computer computer or URLs are no different, except for the method of obtaining an image and its saving. The general loading scheme of the picture on the server is as follows:

To validate the picture on the URL, we will use the GETIMAGESIZEFROMSTring () function, since curl downloads it into a variable for further manipulations.

As we load images to the server, it would be good to check their specific parameters: width, height, a type Pictures, the size file in bytes. It depends on the logic of your application, but for clarity in this manual, we will check all the parameters described above.

§2. Safety regulations

The safety of image loading is reduced to preventing the alien code to the server and its execution. In practice, loading pictures The most vulnerable place in PHP applications: sHELL Script, will a malicious code in binary files, signing EXIF \u200b\u200bdata. In order to avoid most of the hacking methods, you need to follow the following rules:

but not trust data from $ _files;
b. not check the MIME type of pictures from the GetImageSize () function;
in the downloadable file, generate a new name and expansion;
g Prohibit the execution of PHP scripts in the picture folder;
d. not insert user data via Require and Include;
e for $ _Files Use IS_UPLOADED_FILE () and MOVE_UPLOADED_FILE ().

If there is something to add "security rules", then leave your comments or references to safety articles in the comments to this guide, and I publish them in this paragraph.

§3. PHP.INI configuration

PHP allows you to make specific configuration values \u200b\u200bin the process of downloading any files. To do this, it is necessary in the php.ini file to find blocks " Resource Limits.», « Data Handling"And" File Uploads.", And then edit, if necessary, the following values:

; Maximum execution time of the script in seconds max_execution_time \u003d 60. ; Maximum memory consumption with one script Memory_Limit \u003d 64m. ; The maximum allowable size of the data sent by the POST method post_max_size \u003d 5m. ; Permission to download files File_uploads \u003d ON. ; Folder for storing files during download Upload_TMP_DIR \u003d Home / User / Temp ; Maximum size of the downloaded file Upload_max_FileSize \u003d 5m. ; Maximum allowed number of simultaneously downloadable files Max_File_uploads \u003d 10.

Based on the specified values, the user will not be able to upload more than ten files at once, and each file should not exceed 5 MB. Parameters from the block " Resource Limits.»We are more needed to download a remote file, since with CURL, we will download the contents to the variable and check it on the criteria we need, and for this you need extra time and memory.

The PHP.ini configuration file is always needed to configure according to the business logic of the web application being developed. For example, we plan to upload no more than ten files up to 5 MB, which means we need to be needed ~ 50 MB of memory. In addition, we need to know the maximum loading time of one file from the local machine and on the link to set a sufficient execution time of the script in max_execution_time and not scare users errors.

§four. Loading pictures from the form

Now we will not consider the download of multiple files to the server, and we will analyze only the download mechanics itself on the example of one file. So, to load a picture from a computer computer, you must use the HTML form to send the PHP script file using the POST method and specify the data encoding method enctype \u003d "MultiPart / Form-Data" (In this case, the data is not encoded and this value is applied only to send binary files). With the form below we will work further:

For the file selection field, we use the name. name \u003d "Upload" In our HTML form, although it can be any. After sending the file PHP script file-handler.php it can be intercepted using a superglobal variable $ _Files ["Upload"] With the same name that in the array contains file information:

Array ( \u003d\u003e Picture.jpg. // Original File Name \u003d\u003e image / jpeg // MIME file type \u003d\u003e Home \\ user \\ temp \\ phpd07e.tmp // binary file \u003d\u003e 0 // error code => 17170 // file size in bytes)

Not all data from $ _Files. You can trust: MIME-type and file size can be faked, since they are formed from an HTTP response, and the extension in the file name should not be trusted due to the fact that a completely different file may be hidden. However, further, we need to check whether our file is loaded correctly and whether it boot at all. To do this, check errors in $ _Files ["UPLOAD"] ["error"] And make sure the file is loaded by the POST using the function is_uploaded_file (). If something is not on the plan, it means that we take the error on the screen.

// Rebaptize variables for convenience $ filepath \u003d $ _files ["Upload"] ["TMP_NAME"]; $ errorcode \u003d $ _files ["Upload"] ["error"]; // Check for errors if ($ errorcode! \u003d\u003d upload_err_ok ||! Is_uploaded_file ($ FilePath)) ( // array with error names $ errormessages \u003d [upload_err_ini_size \u003d\u003e "The file size exceeded the update_max_filesize value in the PHP configuration.", Upload_err_form_size \u003d\u003e "The size of the downloaded file exceeded the MAX_FILE_SIZE value in HTML-form.", Upload_err_partial \u003d\u003e "The download file was obtained only partially.", Upload_err_no_file \u003d\u003e "The file was not loaded.", Upload_err_no_tmp_dir \u003d\u003e "There is no temporary folder.", Upload_err_cant_write \u003d\u003e "Failed to record a file to disk.", Upload_err_extension \u003d\u003e "PHP extension stopped downloading a file.", ]; // Set the unknown error $ unknownMessage \u003d. "An unknown error occurred when downloading the file."; // If there is no error code in the array, let's say that an error is unknown $ OutputMessage \u003d Isset ($ errorMessages [$ errorcode])? $ ErrorMessages [$ errorcode]: $ unknownMessage; // withdraw the name of the error DIE ($ OutputMessage); )

In order for the attacker not loaded the malicious code built into the image, you can not trust the functions getimagesize ()which also returns the MIME type. The function expects the first argument to reference to the correct image file. You can define a real MIME type of picture through the FileInfo extension. The code below will check the presence of a keyword image. In the type of our downloadable file and if it does not turn out, it will give an error:

// Create a resource FileInfo $ fi \u003d finfo_open (fileinfo_mime_type); // We get MIME type $ MIME \u003d (String) Finfo_file ($ FI, $ FilePath); );

At this stage, we can already upload absolutely any pictures on our server that has been checking on the MIME type, but to load images on certain characteristics, we need to validify them using the function getimagesize ()which might be a binary file $ _Files ["Upload"] ["TMP_NAME"]. As a result, we obtain an array of 7 elements:

Array (\u003d\u003e 1280 // Width \u003d\u003e 768 // Height \u003d\u003e 2 // Type \u003d\u003e width \u003d "1280" height \u003d "768" // Attributes for HTML \u003d\u003e 8 // Color depth => 3 // Color model \u003d\u003e image / jpeg // MIME-type)

For further validation of the image and work on it, we need to know only 3 values: width, height and the size File (to calculate the size apply function fileSize () For a binary file from a temporary folder).

// Result Function Write in a variable $ image \u003d getimagesize ($ FilePath); $ LimitBytes \u003d 1024 * 1024 * 5; $ limitwidth \u003d 1280; $ limitheight \u003d 768; // Check the desired parameters If (FileSize ($ FilePath)\u003e $ LimitBytes) DIE ( "The image size should not exceed 5 MB."); if ($ image\u003e $ limitheight) DIE (); if ($ image\u003e $ limitwidth) DIE ();

After all the checks, we can with confidence to move our downloadable file to some pictures folder. Do better through the function move_uploaded_File ()which works in safe mode. Before moving the file, you can not forget generate a random name and expansion from the image type For our file. That looks like:

// Generate a new file name based on MD5-hash $ Name \u003d MD5_File ($ FilePath); // Socil .jpeg before .jpg.// Move the picture with a new name and extension to the folder / PICS if (! move_uploaded_file ($ filepath, __dir__. "/ Pics /". $ Name. $ Format)) (DIE ( "An error occurred when writing an image."); }

This is completed on this. For more convenient downloads of files, you can use the UploadedFile class from the Symfony Httpfoundation package, which is a wrapper for $ _Files. and also saves the file through move_uploaded_File ().

§five. Loading the image by reference

To download the image by reference, we need a CURL library that works with remote resources. With it, we will download content in the variable. On the one hand, it may seem that for these purposes it will be file_Get_Contents ()But in fact we will not be able to control the volume of downloadable data and normally process all errors. In order for CURL correctly downloaded the data we need: Allow to follow redirectsEnable checks certificatePoint maximum time CURL works (formed due to the volume of downloadable data and the average speed with a resource). How to download the file to the variable shown below with the necessary parameters:

// somehow we get a link $ url \u003d "https://site.ru/picture.jpg"; // Check HTTP in the link address if (! preg_match ("/ ^ Https?: / i", $ URL) && filter_var ($ URL, FILTER_VALIDATE_URL)) (DIE ( "Specify the correct link to the remote file."); } // Start CURL with our reference $ ch \u003d curl_init ($ URL); // Specify the settings for CURL CURL_SETOPT_ARRAY ($ CH, [ // Specify the maximum work hours of CURL Curlopt_timeout \u003d\u003e 60, // Allow to follow redirects Curlopt_followlocation \u003d\u003e 1, // Allow the result to write in a variable Curlopt_returntransfer \u003d\u003e 1, // Turn on the data load indicator Curlopt_noprogress \u003d\u003e 0, // Paint the buffer size 1 KB Curlopt_buffersize \u003d\u003e 1024, // Write a feature for counting downloaded data // Read more: http://stackoverflow.com/a/17642638 Curlopt_progressFunction \u003d\u003e Function ($ CH, $ DWNLDSIZE, $ DWNLD, $ upldsize, $ UPLD) ( // When it is downloaded more than 5 MB, CURL will interrupt work if ($ DWNLD\u003e 1024 * 1024 * 5) (Return - 1;)), // Turn on the certificate check (by default) Curlopt_ssl_verifypeer \u003d\u003e 1, // Check the name of the certificate and its coincidence with the specified host (by default) Curlopt_ssl_verifyhost \u003d\u003e 2, // Specify the verification certificate // Download: https://curl.haxx.se/docs/caextract.html Curlopt_cainfo \u003d\u003e __dir__. "/CACERT.PEM",]); $ RAW \u003d CURL_EXEC ($ CH); // Download the data to the variable $ info \u003d CURL_GETINFO ($ CH); // We get information about the operation $ error \u003d curl_errno ($ CH); // Write the code of the last error // Complete CURL session CURL_CLOSE ($ CH);

If everything passed successfully and the CURL met in 60 seconds, then the contents on the link will be downloaded to the variable $ Raw.. In addition, the function cURL_GETINFO () Return information about the requested request, from where we can get more information for analyzing work with remote resources:

Array ( \u003d\u003e image / jpeg // Mime-type from Content-Type => 200 // Last HTTP code => 0 // Number of redirects => 0.656 // Total Curl Time => 0.188 // Time to connect with the host => 4504 // Real size of the data => 4504 // Data size from Content-Length /* ... */ )

Next, we need to check if there are no mistakes in curl_errno () And make sure that the resource gives the HTTP code equal to 200, otherwise we will say that it was not found for such a URL. After all checks variable $ Raw. Transfer B. getImagesTring () And we work already on the exhaust scheme as in the case of the loading of the pictures from the form.

Please note that we win the size of the file at the time of receiving data, since we cannot trust CURL_GETInfo (), since the content_type, http_code values, download_content_length are formed based on the HTTP headlines received. Download the file completely, and then check the number of bytes will require a lot of time and memory. Therefore, we controlled the size of the obtained data using the curlopt_progressFunction option: as soon as CURL gets more data than our limit, it will stop work and give the CURLE_ABORTED_BY_CALLBACK error.

// Check the CURL errors and the availability of the file if ($ error \u003d\u003d\u003d CURLE_OPERATION_TIMEDOUT) DIE ( "Expectancy limit exceeded."); if ($ error \u003d\u003d\u003d CURLE_ABORTED_BY_CALLBACK) DIE ( "The size should not exceed 5 MB."); If ($ info ["http_code"]! \u003d\u003d 200) DIE ( "File not available."); // Create a resource FileInfo $ fi \u003d finfo_open (fileinfo_mime_type); // Receive MIME-type using the contents of $ RAW $ Mime \u003d (String) FINFO_BUFFER ($ FI, $ RAW); // Close the resource FileInfo FINFO_CLOSE ($ FI); // Check the keyword image (image / jpeg, image / png, etc.) if (STRPOS ($ MIME, "Image") \u003d\u003d\u003d False) DIE ( "You can only download images."); // Take the image data from its contents. $ image \u003d getimageSizeFromString ($ RAW); // Set the restrictions for the pictures $ limitwidth \u003d 1280; $ limitheight \u003d 768; // Check the desired parameters if ($ image\u003e $ limitheight) DIE ( "The height of the image should not exceed 768 points."); if ($ image\u003e $ limitwidth) DIE ( "The image width should not exceed 1280 points."); // Generate a new name from MD5-hash image $ Name \u003d MD5 ($ RAW); // Generate file extension based on image type $ extension \u003d image_type_to_extension ($ image); // Socil .jpeg before .jpg. $ Format \u003d STR_REPLACE ("JPEG", "jpg", $ extension); // Save the picture with a new name and extension to the folder / PICS if (! file_put_contents (__dir__. "/ Pics /". $ Name. $ Format, $ RAW)) (DIE ( "An error occurred while saving an image."); }

You can use the image to save file_Put_Contents ()which will record content to the file. New file name We will create through the function mD5 ()and extension will make from image_type_to_extension (). Now we can upload any pictures on the link.

§6. Setting up a selection of multiple files

In this section we will analyze the methods for downloading multiple images at once from the local user machine and on remote links. We use links to send links $ _Post. and let us give it all the data using the tag textarea.. To download files from the form, we will continue to work on $ _Files.. Our new HTML form will be a little different from the old one.

At the end of the file selection field name name \u003d "Upload" Figured braces and attribute added multiPlewhich allows the browser to select multiple files. All files are downloaded again in a temporary folder if there are no errors in php.ini. You can intercept them in $ _Files.But this time the superglice variable will have an uncomfortable structure for data processing in the array. This task is solved by small manipulations with an array:

// Change the $ _Files structure Foreach ($ _files ["Upload"] AS $ Key \u003d\u003e $ value) (foreach ($ Value AS $ k \u003d\u003e $ V) ($ _files ["Upload"] [$ k] [$ Key] \u003d $ V; ) // Remove old keys Unset ($ _files ["Upload"] [$ Key]); ) // Load all the pictures in order Foreach ($ _Files ["Upload"] as $ k \u003d\u003e $ v) ( // load one file $ _Files ["Upload"] [$ k] ["TMP_NAME"]; $ _Files ["UPLOAD"] [$ k] ["error"]; )

To download several pictures on the URL, let's give our links through textarea. With name name \u003d "Upload"where they can be specified through a space or from a new line. Function preg_split. Disaster all data from $ _POST ["Upload"] And it will form an array in which you need to walk the cycle and each valid URL send to the handler.

$ data \u003d preg_split ("/ \\ s + /", $ _post ["upload"], - 1, preg_split_no_empty); Foreach ($ Data AS $ URL) ( // Validating and load the picture on the URL }

Creating an empty picture.

Syntax:

Int ImageCreate (int x, int y)

Creates an empty picture size x. on the y. Points and returns its identifier. After the picture is created, all work with it is carried out through this identifier, by analogy with how we work with the file through its descriptor.

Example:

Creating a new picture with GD. and withdrawing it to the browser screen:

imageCreateFromPNG.

Creating a picture from the PNG file.

Syntax:

Int ImageCreateFromPNG (String Filename)

This function load images from the PNG file to memory and returns it to the identifier. As after the call imagecreate ()

Example:

An example of finding an error when opening a graphic file.

FUNCTION LOADPNG ($ imgname) ($ im \u003d @imageCreateFromPNG ($ imgname); / * Attempt to Open * / if (! $ Im) (/ * See iF it failed * / $ im \u003d imagecreate (150, 30); / * Create a blank image * / $ bgc \u003d imagecolorallocate ($ im, 255, 255, 255); $ TC \u003d imageColorallocate ($ im, 0, 0, 0); imagefilledRectangle ($ im, 0, 0, 150, 30, $ BGC); / * Output An errmsg * / imagestring ($ im, 1, 5, 5, "error loading $ imgname", $ tc);) Return $ im;)

imageCreateFromjpeg.

Creating a picture from a JPEG file.

Syntax:

Int ImageCreateFromjpeg (String Filename)

imagecreate (), Further work with the picture is possible only through this identifier. When booting from a disc, the image is unpackled and stored in memory already in an unpacked format, so that you can make different operations with it, such as scaling, drawing lines, etc.

imageCreateFromgif

Creating a drawing from the GIF file.

Syntax:

Int ImageCreateFromgif (String Filename)

This feature load images from the file to memory and return its identifier. As after the call imagecreate (), Further work with the picture is possible only through this identifier. When booting from a disc, the image is unpackled and stored in memory already in an unpacked format, so that you can make different operations with it, such as scaling, drawing lines, etc.

It is worth mentioning that GD. Starting from version 1.6 does not support GIF format. In this regard, this function is practically not used.

imagepng.

The function displays an image in a PNG format to any browser or to a file.

Syntax:

Int imgepng (int im [, String FileName])

This feature saves the image specified by its identifier and in memory, to the disk, or bring it to the browser.

imagecreate () iM..

If the argument fileName. Content-Type. Header ().

Header ("Content-Type: Image / PNG") For PNG.

Example: An example of using the function imagepng ():

To save the Alpha-channel source image, use the function imageSavealpha ():

imageJpeg.

Squeeze the picture JPEG browser or saving it in the file.

Syntax:

Int imagejpeg (int im [, String Filename [, Int Quality]]

This feature saves the image specified by its identifier and in memory to the disk, or displays it to the browser.

Of course, at first an image must be loaded or created using a function. imagecreate (). We need to know his identifier iM..

If the argument fileName. omitted, then compressed data in the appropriate format is displayed directly into the standard output stream, i.e. In the browser. The desired title Content-Type. It is not displayed, in view of which you need to withdraw it manually using Header ().

In fact, you must call one of three commands, depending on the type of image:

Header ("Content-Type: Image / JPEG") For jpeg

Third Optional Parameter quality. Sets the image quality (from 0 to 100).

image2wbmp

Displaying the image into a browser or file.

Syntax:

Int Image2WBMP (Resource Image [, String Filename [, int threshold]])

The function displays an image specified by the descriptor image., in the browser, or to a file whose name is set by an optional parameter fileName..

If the image is displayed in the browser, you must specify it type WBMP as image / vnd.wap.wbmp feature Header ():

Function image2wbmp () Available Php. only if the library version GD. 1.8 or lower.

imagegif.

Sending a picture of the GIF browser or saving it in the file.

Syntax:

Int imagegif (int im [, String FileName])

The function save the image specified by its identifier and in memory to disk, or output it to the browser.

Of course, at first an image must be loaded or created using a function. imagecreate (). We need to know his identifier iM..

If the argument fileName. omitted, then compressed data in the appropriate format is displayed directly into the standard output stream, i.e. In the browser. The desired title Content-Type. It is not displayed, in view of which you need to withdraw it manually using Header ().

In fact, you must call one of three commands, depending on the type of image:

Header ("CONTENT-TYPE: Image / GIF")

Because library GD.Starting with version 1.6, does not support the GIF format, this function is rarely used.

imageCopy.

Copying part of the pattern.

Syntax:

Int imagecopy (int dst_im, int src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

The function copies the rectangular area from the standpoint ( sRC_X., src_y.) Width src_w. and height src_h. From drawing src_im in drawing dST_IM., giving a copied offset area ( dST_X., dST_Y.).

The following example will be picture file1.png. entirely copied by B. file2.png.

imagecopyresized

Copying a piece of pattern with scaling.

Syntax:

Int imagecopyresized (int dst_im, int src_im, int dstx, int dty, int srcx, int srcy, int dstw, int dsth, int srcw, int srch)

This feature is one of the most powerful and universal. Using it, you can copy images (or their sections), move or scaling them.

dST_IM. Specifies the image identifier in which the result of the function will be placed. This image should already be created or loaded and have proper dimensions.

src_im - An image identifier over which work is carried out. However, src_im and dst_immogut and coincide.

Parameters sRCX., sRCY., srcw., srch Specify the area inside the source image above which the operation will be carried out - respectively, the coordinates of its upper left corner, width and height.

Finally, the Four dSTX., dty., dSTW., dSTH Specifies the place in the image dST_IM.which will be "squeezed" the rectangle specified in the previous four. Note that if the width or height of two rectangles do not coincide, the picture will automatically be designed to stretch or compressed.

In the following example file1.jpg. decreases twice and writes to the file file2.jp.g:

imageDestroy

Destruction pattern.

Syntax:

Int ImageDestroy (int im)

The function destroys the descriptor iM. Previously created pattern (like closing a file fClose () After opening fopen ()).

If you are an avid php developer, you probably not only heard about the GD Library graphics library. For those who are not familiar with it, I explain the GD Library allows you to create images, modify and manage them without much effort. Today, we will get acquainted with the Aza use in the PHP graphic library GD Library.

Primarily

Make sure the GD library is installed and activated on your server. Do not know how to do it? Do not worry, everything is simple! You just need to create a PHP file on the server, then enter the following:

Now open the browser page and you will see a huge list of features of your PHP version. Scroll down a bit down, find the 'GD' section and make sure the library is connected. If not, contact the company hosting a hosting service. Fortunately, on most servers, on which I have already managed to work and work, the GD library is installed and connected.

Highlights

Let's go through some major moments. First, we will make it so that all error reports are issued by the browser. This can be achieved by entering the following at the very beginning of your PHP code:

Error_Reporting (E_ALL);
?>

Draw a square

Let's start with the simplest and draw with the help of PHP a blue square - nothing supernatural, of course, but it is necessary to deal with the basics. To get the desired square, you must perform the following actions:

Set the content type as "image" so that the browser can interpret the image properly;
. Create a new empty image by setting the desired width and height;
. Make color background blue;
. Save the final image option and transfer it to the browser;
. Clear memory that was used to create and storing the image;
. Organize image display from index.php file

Now that we have decided on the procedure of action, you can start coding. I tried to comment on each line of the code, and about the functions used in the encoding process, then I will talk later. So, here is the code to create our blue square. After writing, we will save it under the name 'basic_square.php'.

// Install the display of error messages
ini_set ("display_errors", "1");
Error_Reporting (E_ALL);


// Determine the image dimensions
// 125px width, 125px height
$ image \u003d imagecreate (125, 125);

// Choose the background color
$ blue \u003d imagecolorallocate ($ image, 0, 0, 255);

// Set another color - just to make sure that when the pattern is displayed, the background will be the color set first ()
// Note - the square will be blue, not red.
$ red \u003d imagecolorallocate ($ image, 255, 0, 0);

// Save the file in PNG format and display it.
imagepng ($ image);

// Clean the memory used
imageDestroy ($ image);
?>

Now let's consider all the functions used and each step of the above code in order to better understand what we do in it:

As I already explained, we add an error message option to quickly fix them if necessary
. Then we use the header () function to set the content type - PNG
. We save the image and install the desired width and height - see ImageCreate () in more detail.
. Then use the imagecolorallocate function to select blue color for the background of our drawing. Please note that in the final version there will be a color installed first, so our square will turn out to be blue, not red.
. For the final storage of the picture, we use imagepng (). If you wish to save the picture in any directory, you must enter additional parameters.
. And finally, we clean the memory using the function of the imagedestroy ()

We can look at the square by us by opening the Blue_Square.php file, and it will be even better if we set a link to it on the main page:

If everything was done correctly, you will see this blue square:

Hello World

Now, when we learned how to create images, let's try to make an image with the text written by our selected font. We can use any font from the TrueType font (.tff) directory. In the following examples, I will use the 'Advent' font. Let's write "Hello WORLD" on a dark gray square. Attention, look at the code, and then disassemble every step in detail.

ini_set ("display_errors", "1");
Error_Reporting (E_ALL);


Header ("Content-Type: Image / PNG");

// Determine the size of the image - 300x300 pixels

// Install the background dark gray

// Indicate the path to the font
$ font_path \u003d "advent_light";

// We write text
$ string \u003d "Hello World!";

// Connect text and pictures
ImageTTFTEXT ($ image, 50, 0, 10, 160, $ white, $ font_path, $ string);

// Save the image
imagepng ($ image);

// Clean the memory
imageDestroy ($ image);
?>

Save the code in the 'hello_world.php' file, we will open it in the same way as it was listed above. So what's new here?

We set the image size of 300 * 300 pixels and used a dark gray background
. Please note how we pointed out the path to the font using the font name: the fact is that further in the code we will have to apply text to the image. Also, do not forget that the name of the font is written without expansion. However, it depends on what version of the GD library uses PHP: if the name of the font does not start with '/', it will be necessary to extend the TTF - that is, if you do not stand before the name of our font, it will be automatically added to TTF at the end .
. Then we write "Hello WORLD!" and save text for further use
. The most important function used in this code is imagettftext (), requiring instructions 8 of the parameters: path to image, image size, inclination angle, x axis, axis Y, color, font, text (in this order)

Save the code, open it in any way, and you will see this picture:

Turn it!

You noticed that the ImageTTFText function connecting the text and the image is the parameter to position at an angle "? So we can turn our text at any angle. Let's rewrite the code and turn the line on the square.

// Install error messages
ini_set ("display_errors", "1");
Error_Reporting (E_ALL);

// Install the content type
Header ("Content-Type: Image / PNG");

// Determine the size of the image: 300x300 pixels
$ image \u003d imagecreate (300, 300);

// Determine the color of the background - dark gray
$ Dark_Grey \u003d ImageColorallocate ($ image, 102, 102, 102);
$ white \u003d imagecolorallocate ($ image, 255, 255, 255);

// Indicate the path to the font
$ font_path \u003d "advent_light";

// We write text
$ string \u003d "Hello World!";

// Connect text and pictures
ImageTTFTEXT ($ image, 50, -45, 30, 70, $ white, $ font_path, $ string);

// Save the image
imagepng ($ image);

// Clean the memory
imageDestroy ($ image);
?>

Please note, we set the value -45 degrees instead of 0 degrees (as in the previous example) - it's all that is required in order to turn the text. Look at the picture.

How? Interesting? Not? Then let's try to do something more practical.

What is the number today?

We can not only draw pictures yourself, but also use ready! A little encoding, and we will have a calendar that displays the current date (month, day and year). We are looking for a calendar workpiece in the Google, we find an image in format.svg - I changed its size and translated into the PNG format. Look at the workpiece:

Now we have a basis and we can process it using GD and PHP functions. I warn that I do not pretend to be the title of the greatest designer in the world - perhaps the other workpiece and another font would look better on the site. So the design is yours, but for now let's look at the code:

// Install error messages
ini_set ("display_errors", "1");
Error_Reporting (E_ALL);

// Install the content type

// Keep the date
List ($ MONTH, $ Day, $ year) \u003d Explode ("/", date ("f / js / y"));

// download the background image
$ image \u003d imagecreatefrompng ("calendar_blank.png");
$ image_width \u003d imagesx ($ image);

// Determine the background color and font
$ white \u003d imagecolorallocate ($ image, 255, 255, 255);
$ black \u003d imagecolorallocate ($ image, 0, 0, 0);
$ font_path \u003d "advent_light";

// specify the position of the text
$ POS_MONTH \u003d ImageTTFBBOX (13, 0, $ Font_Path, $ MONTH);
$ POS_Day \u003d ImageTTFBBOX (25, 0, $ font_path, $ day);
$ POS_YEAR \u003d ImageTTFBBOX (8, 0, $ font_path, $ year);

// I write a month
ImageTTFTEXT ($ image, 13, 0, ($ image_width - $ POS_MONTH) / 2, 40, $ White, $ Font_Path, $ MONTH);

// write day
ImageTTFTEXT ($ image, 25, 0, ($ image_width - $ POS_Day) / 2, 80, $ Black, $ font_path, $ day);

// We write year
ImageTTFTEXT ($ image, 8, 0, ($ image_width - $ POS_YEAR) / 2, 100, $ Black, $ font_path, $ year);

// Save the image
imagejpeg ($ image, "", 100);

// Clean the memory
imageDestroy ($ image);
?>

So, what are we doing here? What is the List () function? Let's figure it out:

As always, we set the type of content so that the picture is displayed correctly.
. In the 10th line you see the List Function feature. We define the date format using the Explode () function and save it. Thus, you can arrange any information. Now we have access to information about the current month, day and year.
. In the Strings 22-24, we use the ImageTTFBBOX () function to organize the date format. The function ensures the display of the date in the specified order, and for access to the right lower corner we write $ POS_MONTH. All this is necessary in order for the text to be automatically placed correctly, regardless of its size.
. Then we create each line in turn and set the size of the text along the X axis.

If no catastrophe occurred, you should have the picture presented below, with the only difference that the date will be the one that is installed on your computer - my drawing, as you can guess, static. For the help with the script thanks to the Catpin site.

Cats and image filters

The last thing I will teach you today, these are filters of images - a very interesting thing, believe me. The imageFilter () feature takes the finished image and changes it in a certain way - for example, it translates into black and white mode. Let's look at the picture with which we will work in its original form.

Now let's make a cat black and white using the image filtering function.

// Install error messages
ini_set ("display_errors", "1");
Error_Reporting (E_ALL);

// Check if the original image is set
if (isset ($ _ get ["source"])) (
// Perform the basic processing of the drawing
$ image \u003d Filter_Var ($ _ get ["source"], filter_sanitize_string);

// Upload an image
$ image \u003d imageCreateFromJPEG ($ image);

// Translate it into black and white mode
ImageFilter ($ image, img_filter_grayscale);

// Install the content type
Header ("Content-Type: Image / JPEG");

// Keep the image as 90%
imagejpeg ($ image, "", 90);

// Clean the memory
imageDestroy ($ image);
}
?>

The above script is flexible enough, so you can easily make any drawing black and white - like this:

We put in the "source" any picture, and soon it will become black and white. Those who plan to use this feature on publicly available servers will require additional security measures. Although in the above script it is a type of type. JPEG, you can use the function to process any graphic files. Now our cat looks like this:

Other filters:

At the end of the lesson, I will introduce you to some other graphic filters and the results of their use.

Brightness filter

For the brightness of the image corresponds to the third parameter:


// The third parameter sets the brightness level of the image.
ImageFilter ($ image, IMG_FILTER_BRIGHTNESS, 40);
imagejpeg ($ image, "", 90);
imageDestroy ($ image);
?>

Gaussian blur

Blur over Gauss, no additional parameters

Header ("Content-Type: Image / JPEG");

$ image \u003d imagecreatefromjpeg ("cat.jpg");
ImageFilter ($ image, IMG_FILTER_GAUSSIAN_BLUR);
imagejpeg ($ image, "", 90);
imageDestroy ($ image);
?>

Contrast

The third parameter determines the contrast

Header ("Content-Type: Image / JPEG");
$ image \u003d imagecreatefromjpeg ("cat.jpg");
ImageFilter ($ image, img_filter_contrast, -15);
imagejpeg ($ image, "", 90);
imageDestroy ($ image);
?>

Removing the average value (pattern effect)

No additional parameters.

Header ("Content-Type: Image / JPEG");
$ image \u003d imagecreatefromjpeg ("cat.jpg");
ImageFilter ($ image, img_filter_mean_removal);
imagejpeg ($ image, "", 90);
imageDestroy ($ image);
?>

Color balance

Sets the saturation of red, green, blue, as well as the alpha channel (optional) in the following order

Header ("Content-Type: Image / JPEG");
$ image \u003d imagecreatefromjpeg ("cat.jpg");
// Alpha Channel Parameter Omitted Below AS IT is optional.
ImageFilter ($ image, img_filter_colorize, 50, 0, 0);
imagejpeg ($ image, "", 90);
imageDestroy ($ image);
?>

To new meetings ...

I hope that you have more or less dealt with the GD library in PHP. In the second part, we will look at some advanced techniques and, of course, find out even more interesting. Use the GD library and your creative abilities and be sure to tell me what you got!

Dear participants in the project moving! Today you are waiting for another interesting topic. We are all used to, say, upload new avatars on social networks. But how are they scaled to the desired size? What happens on the server? These and many other questions are waiting for you under the cat.

Yes, if someone is not aware, then in the Internet terminology "Cat" (from the English Cut - cut), this is a place that shares the news for a brief (in the overall list) and a complete presentation.

Many know that I am developing my own website management system called Kogir (Cogear, http://cogear.ru). The story is complex and long, but stubbornly go to the goal.

Let's see the basic aspects of working with images.

The PHP has a built-in GD library. Here is its documentation:

http://php.net/manual/ru/book.image.php.

On this page you will find a huge number of a variety of functions. But do not be afraid. We are interested in quite concrete.

As you can see, working with images so far is happening in the form of procedures (functions), so the object-oriented shell has to write.

The simplest example of working with the image:

We try on the local machine.

Create a file. image.php.(I have a local domain for experiments test.local).

We put in the root of the Test.local site folder: 1.jpg image:

Call in the browser http: //test.local/image.php (in your case, another address).

We find in the folder image 2.jpg:

The proportions are not preserved, as you can see. Because we did not recalculate them.

We will correct our script so that the recalculation takes place:

$ ratio_orig) ($ width \u003d $ Height * $ Ratio_orig;) ELSE ($ Height \u003d $ width / $ ratio_orig;) // Move the image from the File on the web with a change in the scale of ImageCopyResampled ($ image_p, $ image, 0, 0, 0 , 0, $ width, $ height, $ width_orig, $ height_orig); // Display ImageJPEG ($ image_p, "2.jpg", 100);

Let's look at the result:

Since we were recalculated in height, part of the final image turned out to be black (the original color of the created canvas).

What else can you do with the image? Cut it, turn, laying one thing to another, draw on it.

I am sure that you will be interested in my class for working with images. It does not work outside the system, as it is a driver for the gear (module) "Images".

But you will find a lot of interesting things for yourself:

* @Copyright Copyright (C) 2012, Belyaev Dmitry * @license http://cogear.ru/license.html * @link http://cogear.ru * / class image_driver_gd extensions image_driver_abstract (/ ** * Creates an image * / Public Function Create () (Case ImageType_Jpeg: Case ImageType_Jpeg2000: Case ImageType_JPEG2000: $ This-\u003e source \u003d imagecreatefromjpeg ($ this-\u003e info-\u003e file); break; Case ImageType_png: $ THIS- \u003e Source \u003d ImageCreateFromPNG ($ this-\u003e info-\u003e file); ImageColortransparent ($ this-\u003e source, imagecolorallocate ($ this-\u003e source, 0, 0, 0)); imagealphablending ($ this-\u003e source, false); ImageSavealpha ($ this-\u003e source, true); break; case imagetype_gif: $ this-\u003e source \u003d imagecreatefromgif ($ this-\u003e info-\u003e file); ImageColortransparent ($ this-\u003e source, imagecolorallocate ($ this-\u003e source, 0, 0, 0)); imagealphablending ($ this-\u003e source, false); imagesAsavealpha ($ this-\u003e source, true); Break; Case ImageType_ico: $ this-\u003e source \u003d imagecreatefromwbmp ($ this-\u003e info-\u003e File); Break;)) / ** * Destroys the image * / Public Function Destroy () (ImageDestroy ($ this-\u003e source); IS_Resource ($ this-\u003e target) && imageDestRoy ($ this-\u003e target); ) / ** * Creates a target image * * @param Mixed $ Width * @Param Mixed $ Height * / public Function CreateTarget ($ Width, $ Height) ($ this-\u003e target \u003d imageCreaTusolor ($ width, $ height); if ($ this-\u003e info-\u003e type \u003d\u003d imagetype_png or imagetype_gif \u003d\u003d $ this-\u003e info-\u003e type) (ImageColortransparent ($ this-\u003e target, imagecolorallocate ($ this-\u003e target, 0, 0, 0))); ($ THIS-\u003e INFO-\u003e TYPE) imagealphablending ($ this-\u003e target, false); imagesavealpha ($ this-\u003e target, true);) Return $ this-\u003e target;) / ** * Changes the scale of the image * * @param int | String $ width Width * @ Param int | String $ Height Height * @param String $ Fit Width Scaling Type, Height, Fit * @param int | String $ Scale What Images Scaling Any, Up, Down * @return Object Image * / Public Function Resize ($ Width, $ Height, $ fit \u003d "width", $ scale \u003d "any") ($ source_width \u003d $ this-\u003e smartsize ($ width, "width"); $ source_height \u003d $ this-\u003e SmartSize ($ Height, "Height" ); // Check the SWITCH scaling type ($ Fit) (// if you pick Nail in width, then we give a height to the desired proportions of CASE "WIDTH": $ width \u003d $ source_width; $ Height \u003d Round (($ Source_Width * $ this-\u003e info-\u003e height) / $ this-\u003e info-\u003e width); Break; // if the height mount, then give the width to the desired proportions of CASE "Height": $ width \u003d round (((($ this-\u003e info-\u003e width * $ Source_Height) / $ this-\u003e info-\u003e height); $ Height \u003d $ Source_Height; Break; Case "Crop": if ($ this-\u003e info-\u003e width\u003e $ this-\u003e info-\u003e height) ($ width \u003d round ((($ this-\u003e info-\u003e width * $ Source_Height) / $ this-\u003e info -\u003e Height); $ Height \u003d $ Source_Height;) ELSE ($ width \u003d $ source_width; $ Height \u003d Round ((($-\u003e info-\u003e Height * $ Source_width) / $ this-\u003e info-\u003e width);) Break; // Default We simply stretch Default: Case "fit" :) // Check whether the Switch will be made ($ scale) (// if the image is larger than the specified sizes, nothing happens to it "Up": if ($ width< $this->info-\u003e Width && $ Height< $this-> Info-\u003e Height) (Return $ this;) Break; // If an image is smaller than the specified sizes, nothing happens to "DOWN" with it: if ($ width\u003e $ this-\u003e info-\u003e width && $ height\u003e $ this-\u003e info-\u003e height) (Return $ this;) Break; Case "Any": Default: // Not doing anything. Filonym) $ this-\u003e target \u003d $ this-\u003e createtarget ($ width, $ height); If (Image\u003e Target, $ this-\u003e source, 0, 0, 0, 0, $ width, $ Height, $ this-\u003e info-\u003e width, $ this-\u003e info-\u003e height)) ( $ this-\u003e source \u003d $ this-\u003e target; $ this-\u003e info-\u003e width \u003d $ width; $ this-\u003e info-\u003e height \u003d $ height; if ("Crop" \u003d\u003d $ Fit) (Return $ this -\u003e CROP ("Center", "Center", $ Source_Width, $ Source_Height);)) Return $ this; ) / ** * Produces trimming an image * * @param mixed $ x coordinate cutting X * @Param Mixed $ y coordinate cropping y * @param mixed $ width trim width * @param Mixed $ Height pruning height * @return Object Image * / Public Function Crop ($ x, $ y, $ width, $ height) ($ x \u003d $ this-\u003e SmartSize ($ x, "width") - $ width / 2; $ y \u003d $ this-\u003e SmartSize ($ Y , "Height") - $ Height / 2; $ width \u003d $ this-\u003e smartsize ($ width, "width"); $ Height \u003d $ This-\u003e SmartSize ($ Height, "Height"); $ this-\u003e target \u003d $ This-\u003e CreateTarget ($ Width, $ Height); If-\u003e target, $ this-\u003e source, 0, $ x, $ y, $ width, $ height, $ width, $ Height)) ($ this-\u003e source \u003d $ this-\u003e target; $ this-\u003e info-\u003e width \u003d $ width; $ this-\u003e info-\u003e height \u003d $ height;) Return $ this;) / ** * Maging images * / public Function Merge (Image $ image, $ x, $ y, $ percent \u003d 100) ($ x \u003d $ this-\u003e SmartSize ($ x, "width"); $ y \u003d $ this-\u003e Smartsize ($ Y, "Height"); if- (imagecopymerge ($ this-\u003e source, $ image-\u003e getSource (), $ x, $ y, 0, 0 , $ Image-\u003e Object () -\u003e Image-\u003e Width, $ Image-\u003e Object () -\u003e Image-\u003e Height, $ percent)) () Return $ this; ) / ** * Saves an image * / public function save ($ file \u003d , $ options \u003d array ()) ($ this-\u003e target or $ this-\u003e target \u003d $ this-\u003e source; if (STRPOS ($ File , ".") OR $ file \u003d $ this-\u003e info-\u003e file) ($ ext \u003d pathfo ($ file, pathfo_extension); $ EXT \u003d STRTOLOWER ($ EXT);) ELSE ($ EXT \u003d STRTOLOWER ($ File) ; $ file \u003d null;) Switch ($ EXT) (CASE "JPG": CASE "JPEG": $ Options or $ options \u003d 90; ImageJpeg ($ this-\u003e target, $ file, $ options); break; case " GIF ": ImageColortransparent ($ this-\u003e target, imagecolorallocatealpha ($ this-\u003e target, 0, 0, 127)); imagealphablending ($ this-\u003e target, false); ImageSavealpha ($ this-\u003e target, true) ; ImageGIF ($ this-\u003e target, $ file); break; case "PNG": imagealphablending ($ this-\u003e target, false); imagesAsavealpha ($ this-\u003e target, true); if (IS_Numeric ($ Options)) ($ Quality \u003d $ options; $ Filters \u003d PNG_NO_Filter;) ELSE ($ Quality \u003d Isset ($ options ["Quality])? $ Options ["Quality"]: 9; $ Filters \u003d Isset ($ Options ["Filters"])? $ Options ["Filters"]: png_no_filter; ) imagepng ($ this-\u003e target, $ file, $ Quality, $ Filters); Break; ) $ this-\u003e destroy (); ) / ** * Displays an image * / public Function Output ($ Format, $ Options) ($ this-\u003e Save ($ Format, $ Options);))

How does it work in the system? For what is so much code?

See:

$ image \u003d new image ("1.jpg"); $ Image-\u003e Resize (200,200, "width") -\u003e CROP (200,200) -\u003e Save ("2, JPG);

Do you understand? Works with all the necessary formats automatically. Functional, if necessary, can be expanded.

The homework for you will do what is indicated above (to my class) on the local machine. If you wish and time to experiment with the parameters.