How to use PHP to process images in a Linux environment

Source: Internet
Author: User
Tags bz2 final ftp header imagejpeg imagemagick mysql php and

Using PHP to create images is a fairly easy thing to do. As long as you install some Third-party library files and have some knowledge of geometry, you can use PHP to create and process images. PHP currently uses the GD library to process images. Some image functions can be used directly in PHP, but most functions need to install the GD function library. The GD library provides a series of functions for drawing, using colors, processing stored images, and filling operations. The GD library is written by Thomas Boutell in the ANSI C language, while supporting the mapping of Perl and Tcl languages. Since GD is a library that can be built into shared or static, it is very easy to use the GD library for image manipulation in PHP. GD Image Library Working principle see figure 1.



Figure 1 PHP Image invocation principle

GD Library is currently maintained by Boutell company, the official web site is: http://www.boutell.com/gd/, the latest version of this article is: November 03, 2004, 4 released GD 2.0.33.

  A. PHP supported image formats and fonts

The GD library version of PHP supports the following image formats and fonts:

1.PNG

PNG (Portable Network Graphics) is a bitmap file format that stores 32-bit information, and its image quality is much better than GIF. Like GIF, PNG also uses lossless compression to reduce the size of the file. When compressing bitmap data, it uses a variant of the highly acclaimed L Z77 algorithm. At present, more and more software is starting to support this format, in the near future, it may be widely popular throughout the Web. The PNG image can be a grayscale (16-bit) or color (48-bit) or 8-bit indexed color. The PNG image uses a high-speed alternating display scheme that is fast enough to display a low-resolution preview image with only 1/64 of the image information to be downloaded. Unlike GIF, the PNG image format does not support animations. PNG is the true province of PHP support image format.

2.JPEG

JPEG (Joint Photographic Expert Group) is a 24-bit image file format and is an efficient compression format, the file format is the JPEG (joint Image Expert Group) standard Product, The standard, developed by ISO and CCITT (International Telegraph and Telephone Advisory Committee), is a compression standard for continuous-tone still images. Its original purpose is to use 64Kbps communication lines to transmit 720x576 resolution compressed images. By losing very little resolution, you can reduce the amount of storage required for an image to 10% of its original size. Because of its efficient compression efficiency and standardization requirements, has been widely used in color fax, still images, conference calls, printing and news pictures of the transmission. However, the deleted data can not be restored in the decompression, so the JPEG file is not suitable for enlarged viewing, output to print when the quality will be affected. In general, JPEG files are only dozens of KB, and the highest number of colors can reach 24 bits, so it is widely used on the Internet to save valuable network transport resources.

3.WBMP

WBMP (Wireless Bitmap), a wireless bitmap, is an image format designed for mobile communications devices such as mobile phones and PDAs. This format is used for wireless Communication Protocol (WAP) Web pages. WBMP is a 1-bit format, so only two colors are visible: black and white.

4.XBM

XBM (X BitMap) is a graphics file format. is an old but common image file format that is compatible with many of today's web browsers. The X-windows graphical interface (Unix and Linux common GUI) has a component in the C code library Xlib that specifically describes its specification. The XBM format was originally designed to store monochrome system bitmaps, such as icons and mouse pointers. The XBM graph is essentially a C source code file that uses a 16 binary array to represent binary images. X-bitmaps is an interesting choice for generating simple web graphics, and it doesn't require anything else, as long as it has a browser to work with.

5.GIF

GIF (Graphics Interchange Format) is a compressed graphic file format that can be processed on various graphics processing software on various platforms. The data in GIF files is a lossless compression format for continuous tones based on the LZW algorithm. Its compression rate is generally around 50%, it does not belong to any application. At present, almost all of the relevant software support it, the public domain has a large number of software in the use of GIF image files. Because of the Unisys company patent reason (the LZW algorithm used in GIF format involves Unisys's patent) PHP once it does not support GIF format. If you like this format very much, you can download this earlier version in http://www.linuxguruz.org/downloads/gd1.3.tar.gz but it is not recommended. For more information on the GIF format patent issue, please see the page: http://lpf.ai.mit.edu/Patents/Gif/Gif.html.

6. TrueType Fonts

TrueType is the scalable font that both print and screen apply to. First developed by Apple, it is the main font type on the computer today. Bitmap fonts can only display proportions in their single fixed size, and TrueType fonts display proportions in three different sizes.

7. PostScript fonts

PostScript, first developed by Adobe, is a page description language that describes the location and appearance of graphics and text output (usually to PostScript printers). PostScript printers can open text created by any type of font, but to maximize the performance of PostScript, users need dedicated PostScript fonts. PostScript fonts are often referred to as printer fonts.

  Configuring images and font libraries for PHP

Starting with PHP4.3, PHP has bundled its own version of the GD2 library. The PNG, JPEG format is automatically supported on the Windows Platform GD2 Library. If you want to use the PNG format on UNIX, BSD, Linux platforms, you will need to install two dynamic link library libpng and zlib. Can be compiled with a Linux release version of the RPM package or its official web site download source code.

Zlib Library: http://www.gzip.org/zlib/

Note At compile time use the following command-line options:

./configure--with-zlib-dir=/path/to/zlib

Libpng Library: http://www.libpng.org/pub/png/

Note At compile time use the following command-line options:

./configure--with-png-dir=/path/to/libpng

If you want to use JPEG on UNIX, BSD, Linux platforms, you need to install the JPEG-6D library and recompile the GD library. You can download source code compilation at its official website.

JPEG-6D Library: ftp://ftp.uu.net/graphics/jpeg/

Note At compile time use the following command-line options:

./configure--with-jpeg-dir=/path/to/jpeg-6b

If you want to use TrueType fonts on UNIX, BSD, Linux platforms, you need to install a TrueType library. You can download source code compilation at its official website.

TrueType Library: http://www.freetype.org/

If you want to use PostScript Type 1 fonts on Unix, BSD, Linux platforms, you need to install the T1lib library. You can download source code compilation at its official website.

PostScript Type 1 Library: ftp://sunsite.unc.edu/pub/Linux/libs/graphics/

Note At compile time use the following command-line options:

./configure--with-t1lib[=path/to/t1lib]

After all the libraries have been compiled, restart the Apache server and run Phpinfo () to check to see if the new settings are in effect. If the following options appear, see Figure 2.



Figure 2 GD Library Configuration Interface

You can see from Figure 2 that the configuration of images and fonts for PHP has been completed. Now we're ready to start the image creation process.

  third, create image steps

Creating an image in PHP typically requires the following four steps:

1. Create a background image, then the operation but based on this background.

2. Draw outlines on the image or enter text.

3. Output final graphics.

4. Clear all resources in memory.

Let's look at an application instance, a square with a "PHP" tag. The script is as follows:

$height = 300;

$width = 300;

$im = Imagecreatetruecolor ($width, $height);

$white = Imagecolorallocate ($im, 255, 255, 255);

$blue = imagecolorallocate ($im, 0, 0, 64);

Imagefill ($im, 0, 0, $blue);

Imageline ($im, 0, 0, $width, $height, $white);

Imagestring ($im, 4, M, ' PHP ', $white);

Header (' content-type:image/png ');

Imagepng ($im);

Imagedestroy ($im);

? >

Finally, save this little script as si1.php and then access it in a browser, and you can see an image in PNG format 300x300 pixel size, as shown in Figure 3.



Figure 3 PNG image format output to the browser's interface

Here's a detailed explanation for creating the image process:

1. Create a background image

To create or modify an image in PHP, you must first create an image glyph. This provides the calling function: to implement, as follows:

$im = Imagecreatetruecolor ($width, $height)

Then pass two parameters for this function: the first is the new image width, and the second is the new image height. The function returns the symbol for the new image.

2. Drawing, printing text on the image

Drawing and printing text on an image takes two steps: 1. Select the color first. This selects the color for the image by calling the function $im = Imagecreatetruecolor (). Color is determined by the combination of red, green, and Blue (RGB) values. Two colors are used here:

$white = Imagecolorallocate ($im, 255, 255, 255);

$blue = imagecolorallocate ($im, 0, 0, 64);

You then need to use other functions to draw the color into the image. The choice of these functions depends on what you want to draw: a line, arc, multi-lateral line, or text. The above script si1.php, with a total of three functions:

Imagefill ($im, 0, 0, $blue);

This function takes the image marking symbol, the starting coordinates of the drawing area (x and Y), and the color as parameters. {Note that the starting coordinates of the image in PHP begin with the upper-left corner, which coordinates the x=0,y=0. x= the coordinates of the lower right corner of the image $width, y= $height. This is the opposite of conventional drawing habits. }

Imageline ($im, 0, 0, $width, $height, $white);

This function takes the image symbol, the x and Y coordinates of the starting point of the line, and the color as parameters. This starts with a straight line to the lower-right corner of the image ($width, $height) from the upper-left corner (0,0).

Finally we add a total of tags to the image:

Imagestring ($im, 4, M, ' PHP ', $white);

This function takes the image-marking symbol, the font, the starting coordinates of the text (x and Y), and the color as parameters. The number of font parameter values ranging from 1-5. The TrueType fonts are selected here.

3. Output Final Graphics

You can output the image to a browser or to a total file. The example above is output directly to the browser. Consists of two parts:.

A. First tell the Web browser that we're outputting an image instead of text or HTML.

We send a graphics header to "trick" the browser so that it thinks our PHP page is a real image so it can be displayed correctly on the screen. The server sends the information generated by the program to the browser in the form of binary data streams. This uses the function to specify the MIME type of the image to complete:

Header (' content-type:image/png ');

Typically, when you use a browser to accept a total file, the Apache Web server first sends the content as a MIME type. For the PHP page:

Content-type:text/html

B. After sending the header data, the following function is used to output the image data.

Imagepng ($im);

This function sends the output to the browser in PNG format.

C. Clearing resources

When you finish processing a total image, you should use the destroy image symbol, and then return the selected topic resource to the Web server. This calls the function Imagedestroy () Complete:

Imagedestroy ():

Imagedestroy ($im);

This is done to reduce the CPU load. If you do not use this function on the web side there are too many such images to generate tasks that you may find to cause performance degradation.

  four. Application Advanced:

1. Modify the output format:

The above describes the basic settings, we know that PHP supports a variety of image formats, if you want to output in JPEG format, you can modify step 3 will be modified to:

Header (' content-type:image/jpeg ');
Imagejpeg ($im);

Then save the disk and restart the Apache Web server. Then use the browser. Note the format of the upper output of the browser at this point, see Figure 4.



Figure 4 JPEG image format output to the browser's interface

Of course, if you want to output an image to a file instead of a browser, you can do so by modifying the function:

Imagejpeg ($im, $filename);

This will output the image to the filename file in JPEG format.

2. Create a background from another file

The above describes the creation of an image glyph by calling the $im = Imagecreatetruecolor () function. Here is a description of the image by reading an existing image file, then filter the images, change their size or add other images on the basis. Depending on the format of the file being read, it is usually: imagecreatefrompng (), Imagecreatefromjpeg (), and Imagecreatefromgif (), all three functions are named as parameters. In addition to adding an IMG tag directly to PNG and JPEG images, you can also use PHP scripts that can generate images in the SRC attribute. For example:

The above script invokes si1.php and then prints the text in the browser: PHP going

3. Configure the ImageMagick library for PHP

ImageMagick is mainly used for image conversion, editing, combination, special processing, etc., is another very useful image processing tools. It supports processing of images in a variety of formats, with a maximum of 157 formats, including TIFF, JPEG, PNG, PDF, PhotoCD, and GIF, which are currently popular. Image magick also supports dynamic image creation, which is ideal for use on Web pages. Image magick supports processing of images through a command-line approach. In addition, it provides a programming interface that enables advanced users to personalize images with C, C + +, Perl, and Java interfaces. Image magick supports hundreds of kinds of images processing and provides a variety of filtering functions. Image magick is easy to support images format conversion, support transparent images, can make multiple-frame GIF images, image merging and so on. Image operations include scaling, rotation, sharpening, subtractive or special effects processing. And can be saved in a different image format. The ImageMagick library is not part of standard PHP, but you can extend the class library through PHP (PECL is the PHP extension repository from the PEAR packaging system, PECL official website: http://pecl.php.net/package/ It's easy to install this function library. Compared with GD2, ImageMagick library features richer. Especially if you want to create a GIF, especially an animated GIF, then recommend using ImageMagick. ImageMagick official website: http://www.imagemagick.org. Download the installation configuration steps as follows:

#wget http://nchc.dl.sourceforge.net/sourceforge/imagemagick/ImageMagick-5.5.7-35.tar.bz2

#bunzip2 imagemagick-5.5.7-35.tar.bz2

#tar XVF Imagemagick-k-5.5.7-35.tar
#cd imagemagick-5.5.7-35

#./configure ldflags= "-l/usr/lib" cppflags= "-i/usr/include" \
--prefix=/usr/local/imagemagick--enable-shared \
--ENABLE-LZW # Open LZW format Compression #
Make
Make install

wget wget http://pecl.php.net/get/imagick-0.9.11.tgz

mkdir Ext/imagick

Tar zxvf imagick-0.9.11.tgz

Phpize #phpize命令是用来准备 The compilation environment of the PHP Extension library. #

CD Php_src_dir/ext/magickwand # Php_src_dir refers to your PHP source directory #

RM Configure

./buildconf--force

Description: If your PHP installation is not under/usr, you must pull phpize from the bin/directory under your installation directory. For example, if you have PHP installed under/usr/local/php, you need to perform/usr/local/php/bin/ Phpize You can use the command: "which phpize" to view the location, if it is installed through the RPM package can be viewed with this command: "Rpm-qail |grep phpize."

And then do the second compilation of PHP

./configure--prefix=/usr/local/php--with-mysql=/usr/local/mysql \

--with-imagick=/usr/local/imagemagick

--with-apxs=/usr/local/apache/bin/apxs

Make;make Install

After the compilation is complete, restart Apache and run Phpinfo () to check to see if the new settings are in effect. If the following options appear, see Figure 5.



Figure 5 adding ImageMagick library to PHP

You can see from Figure 5 that the image format that can be processed after configuring the ImageMagick library is increased to nearly 150 kinds. ImageMagick can help PHP accomplish a number of tasks to meet your command line image processing needs. Can greatly reduce the burden of work. It can also be used in C, C + +, Perl, Python, Java, and several other languages imagemagick,linux programmers would love to do that. In addition, the latest ImageMagick website already has a plug-in called Magickwand for PHP, also can support PHP. Readers can test themselves. Also, if you want to learn more about PHP image manipulation techniques You can access: http://www.devshed.com, here are many dynamic images of PHP scripts.

Summary: This article is divided into five parts to introduce the Linux platform based on the PHP image manipulation techniques. All scripts in this article are tested in the red Hat Enterprise Linux as 4.0 environment, PHP version 4.3.9,GD library 2.08.

  Small material:

PHP installed after the GD library and image-related functions include:

GetImageSize: Get the long width of the picture.
Imagearc: Draw an arc.
Imagechar: Writes out the horizontal character.
Imagecharup: Write straight characters.
Imagecolorallocate: Match color.
Imagecolortransparent: Specifies the transparent background color.
Imagecopyresized: Copies the new diagram and resizes it.
Imagecreate: Create a new map.
Imagedashedline: Draw dashed lines.
Imagedestroy: End Graphics.
Imagefill: Graphic coloring.
Imagefilledpolygon: Polygon Area coloring.
Imagefilledrectangle: Rectangular area coloring.
Imagefilltoborder: Specifies coloring within the color area.
Imagefontheight: Get the height of the font.
Imagefontwidth: Gets the width of the font.
Imageinterlace: Use interlaced display or not.
Imageline: Draw solid line.
Imageloadfont: Load dot Matrix font.
Imagepolygon: Draw a polygon.
Imagerectangle: Draws a rectangle.
Imagesetpixel: Draw points.
Imagestring: Draw a horizontal string.
Imagestringup: Draws a straight string.
Imagesx: Gets the width of the picture.
Imagesy: Gets the height of the picture.
Imagettfbbox: Calculates the area occupied by TTF text.
Imagettftext: Write TTF text into the diagram.
Imagecolorat: Gets the index value of the specified point color in the diagram.
Imagecolorclosest: Calculates the closest person to a specified color in a color table.
Imagecolorexact: Calculates the specified color index value on the color table.
Imagecolorresolve: Calculates the index value of the specified or closest color on the color table.
Imagecolorset: Configures the color of the specified index on the color table.
Imagecolorsforindex: Gets the color of the specified index on the color table.
Imagecolorstotal: Calculates the number of colors in the diagram.
Imagepsloadfont: Load PostScript font.
Imagepsfreefont: Remove the PostScript font.
The Imagepsencodefont:postscript font is converted into a vector word.
Imagepstext: Write PostScript text into the diagram.
Imagepsbbox: Calculates the area occupied by PostScript text.
Imagecreatefrompng: Take out the PNG pattern.
Imagepng: Create PNG pattern.
Imagecreatefromgif: Take out the GIF pattern.
Imagegif: Create a GIF pattern.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.