O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 16. Manipulating Images

Lots of people stereotype PHP as only being suitable for outputting text, but that's not true—you can use PHP to create complex and dynamic pictures using the GD image extension. This chapter covers many of the GD functions that will allow you to make your own images for your site, either from scratch or by using existing images.

For image manipulation purposes, PHP ships with its own copy of the popular GD library. You used to have to get your own copy of GD and hope it was compatible with your PHP version. This is no longer the case. The copy of GD that ships with PHP will work with that version of PHP.

Getting Started

An important PHP function when working with images is header(). This outputs a HTTP header of your choice; in this situation, we will be sending the content-type header, which tells web browsers what kind of content they can expect through the connection. Popular content types include text/plain for plain text documents; text/html for most web pages; and image/*, where the * is png, jpeg, gif, or MIME types for other picture formats.

As header() sends HTTP headers, it must be used before you send any content through. This is a core HTTP rule—no headers can be sent after content. This is the same thing that stops you from using cookies after you have sent content. The header() function is covered in more detail in Chapter 20, but for now, we will just work with this one aspect of it.

Creating a new image is done with the imagecreate()

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required