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 />

The scale case uses image_scale(), which takes four arguments. The first two are<br />

the target height and width of the new image. Since image_scale() preserves an<br />

image's aspect ratio, you actually only need to provide one of these, and you can<br />

leave the other one NULL, as we've done in the example. If you provide both values,<br />

one of them may end up smaller than specified because of the calculations needed<br />

to preserve the image's aspect ratio. The last argument specifies whether or not<br />

image_scale() should upscale an image when you provide a height and/or width<br />

that is larger than the original. This typically results in a lower quality pixilated<br />

image, so we have specified FALSE.<br />

Finally, the rotate case uses image_rotate(), which takes two arguments. The first<br />

is the number of degrees the image should be rotated to, and the second specifies an<br />

optional background color that should be used to fill in any space left behind by the<br />

rotation. This color should be specified using the color's hex value. In this example,<br />

we rotate 45 degrees and fill the background with purple.<br />

Finally we need to save and display the resulting image:<br />

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

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

}<br />

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

We create a local filename using drupal_tempnam(), which just generates a random<br />

filename we can use when given a path. It may seem tempting to use information like<br />

the file's Twitpic ID or the operation to be performed in the file's name. However, in<br />

this example, these items are passed in through the URL, and this cannot be trusted. It<br />

is possible to create a security problem if you are not very careful using user-submitted<br />

data in filenames, and thus it is best to avoid that, if at all possible.<br />

We can now pass this path, along with our modified image object, to image_save(),<br />

to save our image to the public filesystem. Once saved, it is a simple matter to call<br />

the theme function for images, to generate the necessary HTML for our image to<br />

be displayed. The following is an example of what you would see when requesting<br />

twitpic/munge/7nyr2/rotate:<br />

[ 330 ]

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

Saved successfully!

Ooh no, something went wrong!