The php anthology 2nd edition 2007 - phần 5 pptx

55 312 0
The php anthology 2nd edition 2007 - phần 5 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 8 Images Building a web site can extend your creativity far beyond a display of (X)HTML formatted text, if you so choose. The umbrella term multimedia describes the delivery of many forms of content to your desktop, including sound, text, images, animation, and movies. Where images are concerned, PHP has great capabilities—you can use it to do a whole lot more than simply add static images to your HTML. Would you like to be able to add a watermark to your images, create appropriately sized thumbnails for your web page, or build a graph based on figures stored in your database? Would you like to do all that automatically and on the fly, using nothing but PHP? We’ll cover all this and more in the following pages. To use the examples here, you’ll need the GD image library for PHP. I’ll assume you have GD version 2.0 or higher (bundled with the latest versions of PHP) with Free- type, JPEG, GIF, and PNG support built in. The PHP functions that use the GD library are documented in The PHP Manual. 1 The year 2004 saw the end of patent issues with GIF images, and support for this format in the GD library has been re-enabled since version 2.0.28, which was released with version 4.3.9 of PHP. 1 http://www.php.net/gd/ Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 198 The PHP Anthology Although the GD library supports GIF images again, it’s worth noting that PNG is capable of supporting alpha channel transparency and full 64-bit images, compared with GIF’s 8 bits. In addition, PNG uses a more efficient compression algorithm, reducing the amount of bandwidth required. While this chapter focuses on the technical details of creating, manipulating, and using images and related libraries, you might also like to brush up on the basics. Mike Doughty has a great introduction to working with images and graphics on his web site. 2 How do I specify the correct image MIME type? MIME stands for Multipurpose Internet Mail Extensions, a standard originally conceived to help identify different email content types. MIME has since become the de facto standard for the description of content types on the Internet. When you work with images in PHP, it’s important to have a grasp of the different content types, or you may end up struggling for hours with what’ s actually a simple problem. Solution Generally speaking, your web server must announce content type by way of a special Content-Type header before it sends requested content to the user’s browser, so that the browser knows what to do with the content. For example, here are the headers that a server might send to announce an image in Portable Network Graphics (PNG) format: HTTP/1.1 200 OK Date: Fri, 28 Mar 2003 21:42:44 GMT Server: Apache/1.3.27 (Unix) PHP/4.3.1 Last-Modified: Wed, 26 Feb 2003 01:27:19 GMT Content-Length: 1164 Connection: close Content-Type: image/png 2 http://www.sketchpad.net/readme.htm Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Images 199 The Content-Type header is used to specify the MIME type of the content served in response to a request for the current URL. In this case, the MIME type is im- age/png , which signifies a PNG image. It’s when we generate an image from a PHP script that the MIME type becomes im- portant in PHP. By default, PHP scripts send a MIME type of text/html (denoting an HTML document). So, in instances when your script is sending an image instead of HTML, you’ll need to specify the MIME type with PHP’ s header function. Here’ s an example: <?php header('Content-Type: image/png'); ?> A list of the common MIME types you’ll need for images is shown in Table 8.1. Table 8.1. MIME Types for Images MIME Type Image Format image/jpeg a JPEG File Interchange Format (.jpeg/.jpg) image/png Portable Network Graphics (.png) image/gif Graphics Interchange Format (.gif) image/bmp Windows Bitmap (.bmp) image/xml+svg Scalable Vector Graphics (.svg) a Internet Explorer understands the image/jpeg type, but when uploading a JPEG image, it sends a type of image/pjpeg. How do I create thumbnail images? If your site will allow images to be uploaded, perhaps for display with submitted content, how can you make sure the images displayed will be of a suitable size? If a user uploads a particularly large image, it might destroy the layout of the page when it’s displayed. Solution One solution to this problem is to create thumbnail images, which guarantee that the images displayed never exceed certain height and width values. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 200 The PHP Anthology Building a basic thumbnail is a five-stage process: 1. Load the source image into a PHP variable. 2. Determine the height and width of the original image. 3. Create a blank thumbnail image of the correct size. 4. Copy the original image to the blank thumbnail. 5. Display the thumbnail using the correct content type. Let’s create a thumbnail from a photo in JPEG format. First, we specify the path to the source image, as well as our desired width and height in pixels: thumb.php (excerpt) <?php $sourceImage = 'sample_images/terrier.jpg'; $thumbWidth = 200; $thumbHeight = 200; Next, we use imagecreatefromjpeg to load an image from the file system into a PHP variable: $original. The getimagesize function returns the width and height of the image (we’ll discuss getimagesize further in “How do I resize images without stretching them?”): thumb.php (excerpt) $original = imagecreatefromjpeg($sourceImage); $dims = getimagesize($sourceImage); We then use the imagecreatetruecolor function to create a blank image (in memory, as PHP variable $thumb) into which the thumbnail image will be placed: thumb.php (excerpt) $thumb = imagecreatetruecolor($thumbWidth,$thumbHeight); As the function name suggests, imagecreatetruecolor creates a true color (24-bit) image, as opposed to the palette-based (8-bit) image that the imagecreate function provides. The imagecreatefromjpeg function we used previously creates a true color image from the source file, so we need the thumbnail to be true color as well. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Images 201 The next line in the example code is the point at which the thumbnail image is ac- tually created from the original: thumb.php (excerpt) imagecopyresampled( $thumb, $original, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $dims[0], $dims[1] ); The imagecopyresampled function places a resized version of the image into the blank thumbnail image, resampling along the way to ensure that the image is resized smoothly. An older version of this function, imagecopyresized, changes the size of the image more crudely. The first two arguments to the function represent the destination image, $thumb, and the source image, $original. The imagecopyresampled function is quite flexible and can be used to copy a portion of one image into another. The next four arguments refer to the x and y coordinates of the destination and source image portions, taken from the top-left corner. As we’re only interested in copying the whole image, we supply 0 for all four arguments. The final four arguments represent the width and height of the destination and source image portions. Again, as we wish to copy the whole image, we supply the full dimensions of each image. Refer to The PHP Manual for more information. 3 Finally, after we’ve sent the correct content type header, Content-type: image/jpeg, we use imagejpeg to output the completed thumbnail: thumb.php (excerpt) header( "Content-type: image/jpeg" ); imagejpeg( $thumb ); ?> Figure 8.1 shows the end result. 3 http://www.php.net/imagecopyresampled/ Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 202 The PHP Anthology Figure 8.1. Our first thumbnail While there’s certainly room for improvement, this is a start. How do I resize images without stretching them? Unless the original and thumbnail images happen to share the same width-to-height ratio (or aspect ratio), the process of resizing the images to generate your thumbnails will warp the dimensions of the images. What we really want is a proportionally scaled version of the original, which fits into the blank thumbnail as neatly as pos- sible. Solution It’ s possible to determine the original image’ s dimensions and use these to calculate the proportional dimensions of the thumbnails. The getimagesize function returns an array of useful information about an image. Here’s an example: <?php $sourceImage = 'sample_images/terrier.jpg'; $dims = getimagesize($sourceImage); echo ( '<pre>' ); print_r($dims); echo ( '</pre>' ); ?> The above example will display the contents of the $dims variable: Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Images 203 Array ( [0] => 600 [1] => 450 [2] => 2 [3] => width="600" height="450" [bits] => 8 [channels] => 3 [mime] => image/jpeg ) The first element of the array is the width of the image; the second is its height. The third array element is a number that identifies the type of image, for which a 1 in- dicates the image is a GIF, 2 indicates a JPEG, and 3 a PNG—more values are de- scribed in The PHP Manual. 4 The fourth array element contains a string that’s in- tended to be used within HTML <img> tags. The bits element contains the color depth. 5 The channels element contains a value of 3 for RGB color images and 4 for CMYK. 6 The mime element contains the MIME type. In this section, we’ll write a class called Thumbnail that allows the generation of proportionally scaled images. The class will also make it possible for us to deal with images that are smaller than the thumbnail size, allowing them to be left at their original size if required. The class will be designed to handle PNG and JPEG files only, but can easily be modified to handle other formats. We need to define some custom exceptions for our error handling needs before we start to create our Thumbnail class: Thumbnail.class.php (excerpt) class ThumbnailException extends Exception { public function __construct($message = null, $code = 0) { parent::__construct($message, $code); 4 http://www.php.net/getimagesize/ 5 Eight bits can represent 256 colors, and 8-bit color is known as indexed color. True, or 24-bit color can represent 16,777,216 colors. 6 The RGB (Red-Green-Blue) color model is used for computer displays, while CMYK (Cyan-Magenta- Yellow-blacK) is used for printing. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 204 The PHP Anthology error_log('Error in '.$this->getFile(). ' Line: '.$this->getLine(). ' Error: '.$this->getMessage() ); } } class ThumbnailFileException extends ThumbnailException {} class ThumbnailNotSupportedException extends ThumbnailException {} Our base custom exception class, ThumbnailException, ensures the exception details are logged using the error_log function. The subclasses represent different exception situations that might arise during the creation of the thumbnail. As with any class, we start with the class properties: Thumbnail.class.php (excerpt) class Thumbnail { private $maxWidth; private $maxHeight; private $scale; private $inflate; private $types; private $imgLoaders; private $imgCreators; private $source; private $sourceWidth; private $sourceHeight; private $sourceMime; private $thumb; private $thumbWidth; private $thumbHeight; $maxWidth, $maxHeight, $scale, $inflate, $types, $imgLoaders, and $imgCreators are set by the constructor and are described below. $source, $sourceWidth, $sourceHeight, and $sourceMime represent the properties of the source image and will be set by the image loading methods described below. $thumb, $thumbWidth, and $thumbHeight represent the properties of the created thumbnail and are also described below. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Images 205 Next, we create a class constructor: Thumbnail.class.php (excerpt) public function __construct($maxWidth, $maxHeight, $scale = true, $inflate = true) { $this->maxWidth = $maxWidth; $this->maxHeight = $maxHeight; $this->scale = $scale; $this->inflate = $inflate; The constructor for the Thumbnail class takes four arguments. The first two are the maximum width and height of the thumbnail in pixels, respectively. The third ar- gument tells the Thumbnail object whether it should scale the image to the thumbnail proportionally, or just stretch it, as with the earlier example. The fourth argument tells the Thumbnail object what to do with images that are too small; that is, whether to blow them up to fill the thumbnail. With those arguments safely stored in instance variables, we can create the rest of the constructor: Thumbnail.class.php (excerpt) $this->types = array('image/jpeg', 'image/png', 'image/gif'); $this->imgLoaders = array( 'image/jpeg' => 'imagecreatefromjpeg', 'image/png' => 'imagecreatefrompng', 'image/gif' => 'imagecreatefromgif' ); $this->imgCreators = array( 'image/jpeg' => 'imagejpeg', 'image/png' => 'imagepng', 'image/gif' => 'imagegif' ); } The $this->types property stores an array of the MIME types that this class can handle. The $this->imgLoaders property stores the names of the functions used to load images of those MIME types, while the $this->imgCreators property stores the names of the functions for creating new images of those types. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 206 The PHP Anthology The Thumbnail class provides two methods for loading the image you want to con- vert. The first, loadFile, allows you to specify a local file to load: Thumbnail.class.php (excerpt) public function loadFile ($image) { if (!$dims = @getimagesize($image)) { throw new ThumbnailFileException( 'Could not find image: '.$image); } if (in_array($dims['mime'],$this->types)) { $loader = $this->imgLoaders[$dims['mime']]; $this->source = $loader($image); $this->sourceWidth = $dims[0]; $this->sourceHeight = $dims[1]; $this->sourceMime = $dims['mime']; $this->initThumb(); return true; } else { throw new ThumbnailNotSupportedException( 'Image MIME type '.$dims['mime'].' not supported'); } } The loadFile method uses the getimagesize function to grab all the required image properties, including width, height, and MIME type. If getimagesize returns false, an error has occurred and we throw one of our custom exceptions, ThumbnailFileException. If the MIME type of the image is not on our list of sup- ported types, we throw a ThumbnailNotSupportedException. If all’s well, we load the image via the image loading function that’s appropriate for the MIME type, and assign it to the $this->source property. We also assign the image width to the $this->sourceWidth property, the image height to the $this->sourceHeight property, and MIME type to the $this->sourceMime property. After all the instance variables are set, the method calls the initThumb method, which we’ll tackle in a moment. Finally, having no exceptions, the method returns true. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... Title font $graph->title->SetFont(FF_VERDANA,FS_BOLD,14); Now, let’s construct the x axis Here, the labels are assigned using the SetTickLabels method, ticks being the markers for each interval on the x axis: bargraph .php (excerpt) // Axis title text $graph->xaxis->title->Set('Product Type'); // Axis title color $graph->xaxis->title->SetColor('black'); // Axis title font $graph->xaxis->title->SetFont(FF_VERDANA,FS_BOLD,10);... on the image by specifying the red, green, and blue components The function returns a number, which identifies that color in the image Once you have the color in hand, you can use the imagestring function to place the text over the image The first of the function’s arguments is the image, and the second is a font number the numbers 1 5 refer to built-in fonts You can use imageloadfont to make other... In the above modification to our gallery, if the image is a JPEG image, we add to the display the date the picture was taken, and the make and model of the camera that was used, if those details are available As you can see, the EXIF data appears beneath the appropriate images in Figure 8 .5 219 220 The PHP Anthology Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 8 .5 The. .. use the Thumbnail class we created in the previous section, together with PHP s built-in dir pseudo-class (refer to the section called “Using the dir PseudoClass” in Chapter 6 for more information on the dir pseudo-class) to create our gallery We simply read through the directory, look for images that don’t have thumbnails, and create them; at the same time, we generate the HTML that will display them... image: Thumbnail.class .php (excerpt) if ( $this->sourceWidth maxWidth && $this->sourceHeight maxHeight && $this->inflate == false ) { $this->thumb = $this->source; } else { imagecopyresampled( $this->thumb, $this->source, 0, 0, 0, 0, $this->thumbWidth, $this->thumbHeight, $this->sourceWidth, $this->sourceHeight ); Images Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... Hide ticks $graph->xaxis->HideTicks(); The y axis will take numeric values that are generated automatically once the y data is added: bargraph .php (excerpt) // Axis title text $graph->yaxis->title->Set('Units Sold'); // Axis title color $graph->yaxis->title->SetColor('black'); // Axis title font $graph->yaxis->title->SetFont(FF_VERDANA,FS_BOLD,10); // Axis colors $graph->yaxis->SetColor('black','white');... another slice $pie->ExplodeSlice(3); We’ll display a label next to each segment on the chart to identify the percentage of the whole that segment represents: piechart .php (excerpt) // The font $pie->value->SetFont(FF_VERDANA,FS_NORMAL,10); // Font color $pie->value->SetColor('black'); Finally, we add our pie chart object to the graph object and send it to the browser: piechart .php (excerpt) $graph->Add($pie);... imagecopymerge function are the original or destination image object, and the source image object the watermark, in our case The next four arguments represent the x and y coordinates of the destination image and source image respect­ ively, starting from the top-left corner of the images The following two arguments represent the width and height of the source image The last argument represents the level of transparency... ($this->maxWidth/$this->sourceWidth) ); } else if ( $this->sourceWidth < $this->sourceHeight ) { $this->thumbHeight = $this->maxHeight; $this->thumbWidth = floor( $this->sourceWidth * ($this->maxHeight/$this->sourceHeight) ); } else { $this->thumbWidth = $this->maxWidth; $this->thumbHeight = $this->maxHeight; } } This part of the function will check to ascertain whether or not image scaling is re­ quired If it... constructor: Thumbnail.class .php (excerpt) else { $this->thumbWidth = $this->maxWidth; $this->thumbHeight = $this->maxHeight; } The next step is to create our blank thumbnail image by employing the imagecreatetruecolor function: Thumbnail.class .php (excerpt) $this->thumb = imagecreatetruecolor( $this->thumbWidth, $this->thumbHeight ); The final step in our initThumb method is to copy the source image into . with the latest versions of PHP) with Free- type, JPEG, GIF, and PNG support built in. The PHP functions that use the GD library are documented in The PHP Manual. 1 The year 2004 saw the end. filename. We use the PHP header function together with the getMime method to send the correct HTTP header; then, we simply call the buildThumb method to dis- play the image. The result of our. appropriate for the MIME type, and assign it to the $this->source property. We also assign the image width to the $this->sourceWidth property, the image height to the $this->sourceHeight

Ngày đăng: 13/08/2014, 09:20

Từ khóa liên quan

Mục lục

  • The PHP Anthology

    • Table of Contents

    • Preface

      • Who Should Read this Book?

      • What’s Covered in this Book?

      • Running the Code Examples

      • The Book’s Web Site

        • The Code Archive

        • Updates and Errata

        • The SitePoint Forums

        • The SitePoint Newsletters

        • Your Feedback

        • Conventions Used in this Book

          • Code Samples

          • Tips, Notes, and Warnings

          • Introduction

            • Where do I get help?

              • Solution

                • RTFM: Read the Fine Manual

                  • I. Getting Started and II. Installation and Configuration

                  • III. Language Reference

                  • IV. Security

                  • V. Features

                  • VI. Function Reference

                    • PHP Extensions

                    • User Comments

                    • Other Resources

                    • What is OOP?

                      • Solution

                        • Classes Explained

                          • Encapsulation and Visibility

                          • Constructors and Destructors

Tài liệu cùng người dùng

Tài liệu liên quan