Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Crop to fit - Image resizing (2.4)


5 Posts   1109 Views

Nobrainer Web

31 August 2012 at 2:32am Community Member, 135 Posts


I'm looking for a way to scale an image proportionally, filling a given width and height.
Scaling can not get smaller than the dimensions given.
After downscaling the image, i wont it cropped from center, so the dimension that goes beyond the given size is cropped away.
See explanation and PHP code here:

My question is, can someone show me how to implement the above in SilverStripe, i think it should be done using a class that extends DataObjectDecorator, so it can be easily moved between projects.

Example found on the forums using DataObjectDecorator:

class CustomImage extends DataObjectDecorator {
   function Optimised($width, $height) {
      return $this->owner->getFormattedImage('Optimised', $width, $height);
   function generateOptimised(GD $gd, $width, $height) {
      return $gd->croppedResize($width, $height);

Thank you!


31 August 2012 at 3:22am Community Member, 76 Posts


I am not sure if this helps but I use the following to crop from the center when returning a cropped image in one of my functions.

// ----
// Gets the content of the image at that ID and crops it
// ----
return $image->CroppedImage(213,200);

Nobrainer Web

3 September 2012 at 11:50pm Community Member, 135 Posts

Thank you for your answer ssimples.

It's actually possible to do what i want, with the function:
$image->croppedResize(width,height) // Crops the image from the centre, to given values.

However i don't know how to call that function directly from template, so i just used the code found here:

Works perfect and now i can easily add extensions if i should need that.


Thomas B. Nielsen
[url=]Nobrainer Web[/url]


4 September 2012 at 1:35am Community Member, 215 Posts

You don't need a extension. Just call in the template;



<% control Image %>
<img src="$CroppedImage(150,200).Filename" width="150" height="200" />
<% end_control %>

Nobrainer Web

28 September 2012 at 8:31am Community Member, 135 Posts

You are so right Devlin - ofcourse it's that simple :-)
Wondering why i did not see that, maybe i just misunderstood the documentation.

But nice that the function is ther, thank you.