Snippets - Little bits of code to make you happy
Resizing and Manipulating Images
Tweet22 March 2009 | | | Supports v2.4, v2.3
You can resize images from within the template very easily. But sometimes you need to resize it and just use the URL value, something you can't do by calling the resize on the variable directly (e.g. $Image.CroppedImage(200,200)). This is how we would create a cropped resize of it and still be able to use just the URL, allowing a custom <img> tag.
<% control Image %> <img src="$CroppedImage(200,200).URL" alt="$Title" /> <% end_control %>
You can also use these other GD functions in a control block:
$PaddedImage(200,200) $ResizedImage(200,200) $SetWidth(200) $SetHeight(200)
If you would rather be doing your resizing in PHP, here are the GD functions you can use on image (kindly Supplied by SalvaStripe):
//Very basic resize, just skews the image if necessary $Image->SetSize(width,height); //Resizes an image with a maximum width and height - a useful function $Image->SetRatioSize(width,height); //Adds additional padding if necessary after resizing to width height. $Image->PaddedImage(width,height); //Crops the image from the centre, to the given width and height. $Image->CroppedImage(width,height); //Maximum height the image resizes to, keeps proportion so width is flexible. $Image->SetHeight(height); //Maximum width the image resizes to, keeps proportion so height is flexible $Image->SetWidth(width); //Returns the height of the image. $Image->getHeight(); //Returns the width of the image $Image->getWidth(); //Returns a class constant: ORIENTATION_SQUARE or ORIENTATION_PORTRAIT or ORIENTATION_LANDSCAPE $Image->getOrientation();
4 Comments
RSS feed for comments on this page RSS feed for all comments
DusX
08/10/2010 5:29am (3 years ago)
don't forget the 'new' for 2.4 SetRatioSize.
tomg
19/07/2011 3:16pm (2 years ago)
Thanks for this, been banging my head against my desk for the last half an hour trying to work out how to create some thumbnails, dread to think how many hours you've just saved me :)
Todd
03/08/2011 10:00pm (2 years ago)
Thanks for this! Very helpful. Remember that if you have an image associated to another object, you'll need to use nested control blocks. For example, my Profile objects each have a ProfileImage. So For my template, I need to have a nested control for the Profile Image before I can use the GD functions above.
pinkp
26/02/2013 10:41am (3 months ago)
How can i nest a control in my loop:
<% loop Images %>
<div class="GalleryImage">
<span><h3>$ImageTitle</h3></span>
<a class="fancybox" data-fancybox-group="gallery" href="$Filename" title="$ImageTitle $ImageSubTitle">
$CroppedImage({$Top.WidthImage})
</a>
<% end_loop %>
This does't work, I want to have a cropped image and allow the user to control the sizes in the CMS.
$CroppedImage(280,140)
$CroppedImage({$Top.WidthImage})
thanks
Post a comment ...
You cannot post comments until you have logged in. Login Here.