Jump to:

3434 Posts in 1026 Topics by 866 members

Template Questions

SilverStripe Forums » Template Questions » Using GD resize() on Image objects in a page controller

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

Page: 1
Go to End
Author Topic: 2421 Views
  • david_nash
    Avatar
    Community Member
    55 Posts

    Using GD resize() on Image objects in a page controller Link to this post

    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?

  • david_nash
    Avatar
    Community Member
    55 Posts

    Re: Using GD resize() on Image objects in a page controller Link to this post

    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!)

    2421 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.