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, Ed, biapar, Willr, Ingo, swaiba

Crop to fit - Image resizing (2.4)

Go to End

5 Posts   1575 Views

Nobrainer Web

Community Member, 138 Posts

31 August 2012 at 2:32am


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!


Community Member, 77 Posts

31 August 2012 at 3:22am


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

Community Member, 138 Posts

3 September 2012 at 11:50pm

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
Nobrainer Web


Community Member, 290 Posts

4 September 2012 at 1:35am

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

Community Member, 138 Posts

28 September 2012 at 8:31am

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.