Getting the image dimensions in smarty

Using the height and width of the images and thumbnails in your gallery templates should be pretty straightforward, not? Well i guess it wasn't... Until now!

Last updated on: 20130411 (thx to Calguy1000)
Last tested on: CMSMS 1.11.5
Note: the codes below are supposed to be located inside the main "foreach" in your gallery template but you can use the same concept everywhere!

{foreach from=$images item=image}

1. How can we get the image sizes using a php function?

We use the "getimagesize" php function for this:

{getimagesize($image->file)}

As this outputs an array, we need to use the "print_r" modifier to see the output the php function generates.

{getimagesize($image->file)|print_r}

Using the print_r modifier, we get to see the Array content:

Array (
    [0] => 385
    [1] => 100
    [2] => 2
    [3] => width="385" height="100"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg 
) 1

2. Storing the getimagesize output in an array

Seeing the output using print_r is all fine and dandy but we can't use the values yet in our template just yet!
We need to store the values generated by the getimagesize modifier in an array so we can use them later on.
To achieve this, we assign the output of the getimagesize to a variable (actually it's an array but PHP takes care of this for you automagically)

{assign var=foo value=getimagesize($image->file)}

Or use the "short hand" variation:

{$foo=getimagesize($image->file)}

ps: you can change $image->file to $image->thumb if you are after the thumbnail sizes.

 

3. Using the values we need in our template

All the values are now stored in the $foo array.
To use the values in our template we can now simply call $foo[##NUMBER OF THE VALUE YOU WANT TO USE##]

Width in pixels: {$foo[0]}
Height in pixels: {$foo[1]}
Image type: {$foo[2]}
height="yyy" width="xxx": {$foo[3]}
etc...

4. All done!

I hope you like it, a shout in the comments is appreciated!
If you have something to share, please don't hold back!
You can also post your feedback or comments in the related forum thread.

Greetings,
Manuel

Comments