18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Files and Images<br />

Images in <strong>Drupal</strong><br />

Just as the contributed Filefield module largely handled file handling in <strong>Drupal</strong><br />

6, two modules—Imagefield and Imagecache, largely handled image handling.<br />

Imagefield was used for attaching images to nodes, and Imagecache was used<br />

to create derivations of those images by resizing or cropping them. This was very<br />

popular for things like creating square thumbnails in a grid for image galleries. The<br />

functionality of both modules has been brought into core for <strong>Drupal</strong> 7, along with<br />

an improved API for managing this functionality from code.<br />

Image API<br />

The <strong>Drupal</strong> 7 Image API provides a variety of functions to manipulate images. By<br />

default, <strong>Drupal</strong> uses the GD image management library that is included with PHP.<br />

However <strong>Drupal</strong> also offers the ability to switch to a different library if needed.<br />

For instance, a contributed module could implement the ImageMagick library for<br />

developers who needed support for additional image types such as TIFF, which GD<br />

does not support.<br />

Working with images is similar to working with files. You get an image object by<br />

opening a local image using image_load(), and then pass this object to one of the<br />

image manipulation functions provided by <strong>Drupal</strong>. Once you've performed the<br />

desired modifications to your image, you save it using image_save().<br />

Image API functions can only access files on your local file system.<br />

You can still use stream wrapper schemes like public:// and<br />

private:// to refer to files, but remote file systems will not<br />

function properly.<br />

The following <strong>Drupal</strong> functions are available for image manipulation:<br />

• image_crop(): Crop an image to specified dimensions.<br />

• image_desaturate(): Convert an image to grayscale.<br />

• image_resize(): Resize an image to specified dimensions. This can affect<br />

the image's aspect ratio.<br />

• image_rotate(): Rotate an image to the specified number of degrees.<br />

• image_scale(): Resize an image to specified dimensions without affecting<br />

the image's aspect ratio.<br />

• image_scale_and_crop(): Combine scale and crop in one operation.<br />

[ 326 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!