if it's of use for anybody, I extended the BetterImage class SSBits Image Tutorial with a CroppedFromTopImage function. Thought I'd share it.
So far it centers the cropped image, if you want it to crop from top left adjust the function generateCroppedFromTopImage() (from line 65) according to the comment.
Just a quick hack, I guess it could be done more nicely. Always open to suggestions.
Jonas
Edit: Server fails, when I try to attach the file, so here are the two functions I changed/added:
public function getFormattedImage($format, $arg1 = null, $arg2 = null) {
if($this->ID && $this->Filename && Director::fileExists($this->Filename)) {
$size = getimagesize(Director::baseFolder() . '/' . $this->getField('Filename'));
$preserveOriginal = false;
switch(strtolower($format)){
case 'croppedimage':
$preserveOriginal = ($arg1 == $size[0] && $arg2 == $size[1]);
break;
case 'croppedfromtopimage':
$preserveOriginal = ($arg1 == $size[0] && $arg2 == $size[1]);
break;
}
if($preserveOriginal){
return $this;
} else {
return parent::getFormattedImage($format, $arg1, $arg2);
}
}
}
/**
* Generate a resized copy of this image with the given width & height. Cropped from top-center
* Use in templates with $CroppedFromTopImage.
*/
function generateCroppedFromTopImage($gd, $width, $height) {
if(is_numeric($gd) || !$gd){
USER_ERROR("Image::generateFormattedImage - generateCroppedFromTopImage is being called by legacy code or gd is not set.",E_USER_WARNING);
}else{
if($gd->getWidth / $gd->getHeight >= $width/$height){
$gd = $gd->resizeByHeight($height);
$left = ($gd->getWidth - $width)/2; //center cropped image.
// if you want to cut from top left or right make $left = 0 or $gd->getWidth - $width respectively
}else{
$gd = $gd->resizeByWidth($width);
$left = 0;
}
return $gd->crop(0, $left, $width, $height);
}
}