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.

Template Questions

Using GD resize() on Image objects in a page controller


Reply

2 Posts   2442 Views

Avatar
david_nash

18 March 2009 at 6:33pm Community Member, 55 Posts

I'm writing a function that selects an image at random and returns an image tag. I'd like to scale that image, but I can't work out how.

class HomePage_Controller extends Page_Controller {
...

function RandomImage() {
$galleryItem = DataObject::get_one('GalleryItem', 'MyHomePageID != 0', false, 'RAND()');
$g = DataObject::get_by_id("GalleryItem_ProductImage", $galleryItem->GalleryItemImageID);

//somehow scale $g here

return "<img src=\"$g->Filename\" alt=\"$galleryItem->GalleryItemTitle\" />";   
}

...
}

As I understand it, my get_by_id() call should be returning an Image (GalleryItem_ProductImage extends Image) which means that I should be able to use GD functions on it.

But if I create a new GD object and use resize() it, how do I then get the filename for the src attribute?

Avatar
david_nash

19 March 2009 at 1:28pm (Last edited: 19 March 2009 1:30pm), Community Member, 55 Posts

Here's the workaround that I used. In mysite/code/HomePage.php.

I now have:

function RandomImage() {
   return DataObject::get_one('GalleryItem', 'MyHomePageID != 0', false, 'RAND()');
}

In my template I just wanted to have $RandomImage, which would output an <img scr="blah.jpg" alt="blah"> tag.

Instead I do this in the template:

<% if ClassName = HomePage %>
   <% control RandomImage %>
      <img src="$GalleryItemImage.Scaled.URL" alt="$GalleryItemTitle" class="Logo{$LightLogo}" >
   <% end_control %>
<% end_if %>

RandomImage() returns at GalleryItem, and I used RandomImage to "iterate" through the set of one GalleryItem.

In mysite/code/GalleryItem.php, after the GalleryItem model class I have:

class GalleryItem_ProductImage extends Image {

   function generateScaled($gd) {
      return $gd->resize(552, 561);
   }

} //end class

I'm not really sure why but this allows me to use "$GalleryItemImage.Scaled" in the template. SS chops off the 'generate' part of 'generateScaled' and 'Scaled' returns a GD object, which for some reason I don't understand I can then access its URL property.

I hope this helps someone, and I hope someone else can explain to me the things I don't understand :-)

(ps wow, tabs work in "code" blocks!)