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.

Working with Files and Images<br />

*/<br />

function twitpic_image_munge($id, $operation = 'rotate') {<br />

// If we get a disallowed operation, just return.<br />

$operations = array('rotate', 'desaturate', 'scale');<br />

if (!in_array($operation, $operations)) {<br />

return;<br />

}<br />

$twitpic_uri = 'twitpic://' . $id . '/thumb';<br />

$local_uri = 'public://' . $id . '.jpg';<br />

$twitpic_image = file_get_contents($twitpic_uri);<br />

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

uri, FILE_EXISTS_REPLACE);<br />

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

$local_<br />

switch ($operation) {<br />

case 'scale':<br />

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

break;<br />

case 'desaturate':<br />

image_desaturate($local_image);<br />

break;<br />

}<br />

case 'rotate':<br />

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

break;<br />

$local_uri = drupal_tempnam('public://', $id);<br />

image_save($local_image, $local_uri);<br />

}<br />

return theme('image', array('path' => $local_uri));<br />

The first thing we do is to define our allowed operations, and return if the<br />

operation passed in doesn't match one of them. This allows us to fail gracefully in<br />

that situation. Then we put together the Twitpic URI and grab a local copy of the<br />

Twitpic image using file_get_contents() as we did earlier in the chapter. For the<br />

purposes of this example, we just hardcode the size to thumb, but you could easily<br />

add that as an additional argument, if you wish to do so.<br />

[ 328 ]

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

Saved successfully!

Ooh no, something went wrong!