18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11<br />

After this setup, we start getting into the meat of the function.<br />

$local_path = file_unmanaged_save_data($twitpic_image, $local_uri,<br />

FILE_EXISTS_REPLACE);<br />

$local_image = image_load($local_path);<br />

Since we are not associating this file with any other content within <strong>Drupal</strong>,<br />

we have no need for it to be entered into the files table. Therefore, we use<br />

file_unmanaged_save_data() as opposed to file_save_data(), in order<br />

to prevent unnecessary records from being written.<br />

Once the file is saved, we call image_load() to get back $local_image, a <strong>Drupal</strong><br />

image object that we can pass on to the image manipulation functions. Like the file<br />

object, an image object contains a variety of information about the image that has<br />

been loaded, including its height and width, mime-type, and a handle to the image.<br />

Now that we have an image object, we can mess with it using <strong>Drupal</strong>'s API<br />

functions. For the purposes of this experiment, we just hardcode some sample<br />

manipulations in, to see the kind of things you can do.<br />

switch ($operation) {<br />

case 'desaturate':<br />

image_desaturate($local_image);<br />

break;<br />

case 'scale':<br />

image_scale($local_image, NULL, 50, FALSE);<br />

break;<br />

}<br />

case 'rotate':<br />

image_rotate($local_image, 45, 0x7D26CD);<br />

break;<br />

As you can see, we have three possible manipulations depending on the operation<br />

passed in through the URL. All of these functions work directly on our image<br />

object, $local_image which is passed by reference, so we don't need to worry<br />

about return values.<br />

The first example, image_desaturate(), is the simplest. It just converts the image<br />

to grayscale, with no configuration arguments.<br />

[ 329 ]

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

Saved successfully!

Ooh no, something went wrong!