Rolf-Thomas

ist ein Internetentwickler bei idee[x] digitale dienste

How to generate images in a Typo3 Extbase Controller

20. July 2017

photo by Caspar Rubin

I can't be the only one with this problem, can I?

I searched for hours and hours without any meaningful outcome. The problem being how to generate an image in an Extbase Controller under Typo3 version 8.7.3. In fluid it's easy and well documented:

<f:uri.image src="{image.uid}" treatIdAsReference="1" width="1000" height="500c-100" />

But I hardly found anything about doing the same thing in a controller. The reason for my need was to generated a specific image file for social media sharing to use in og:image and twitter:image metatags.

How to do it

In the end with a little help and consulting the Typo3 API I came up with this solution: (works with Typo3 version 8.7.3)

/**
 * ExampleController
 */
class ExampleController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * @var \TYPO3\CMS\Extbase\Service\ImageService
     * @inject
     */
    protected $imageService;

    // […]

    /**
     * action show
     *
     * @param \Company\Project\Domain\Model\Example $example
     * @return void
     */
    public function showAction(\Company\Project\Domain\Model\Example $example)
    {

        // generate image in controller
        // prerequisite: the model has a mandatory property "image"

        // get image path
        $imagePath = $example->getImage()->getOriginalResource()->getOriginalFile()->getPublicUrl();
        // process image (resize to 1000x500 pixel)
        $processedImage = $this->imageService->applyProcessingInstructions($this->imageService->getImage($imagePath, null, false), ['width' => '1000','height' => '500c-100']);
        // build absolute url (a little bit cheating with the trim…)
        $imageUri = $this->request->getBaseUri().trim($this->imageService->getImageUri($processedImage),'/');

        // add social sharing image to html header
        $headers = [];
        // […]
        $headers[] = "<meta property=\"og:image\" content=\"{$imageUri}\">";
        // […]
        $headers[] = "<meta name=\"twitter:image\" content=\"{$imageUri}\">";
        foreach ($headers as $header) {
            $this->response->addAdditionalHeaderData($header);
        }

        // […]

        $this->view;

    }

You better clear every cache you can – including /typo3temp – after adding @inject into the class.

Also I have the feeling that…

$this->imageService->applyProcessingInstructions(…)

is a little bit underdocumented to say the least. Or did I miss something?

Reactions?

Anything to add or correct? Just reply on the tweet.

How to generate images in a #Typo3 #Extbase #Controller @rolfthomas