Rolf//Thomas

ist ein Internetentwickler bei idee[x] digitale dienste

How to generate images in a Typo3 Extbase Controller

(Aktualisiert am )

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

I searched for some time without any meaningful outcome. The problem is to create an image in a Typo3 Extbase controller. 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:

use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Service\ImageService;

/**
 * ExampleController
 */
class ExampleController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
	private $imageService;

	public function __construct(
		ImageService $imageService
	) {
		$this->imageService = $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
		$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;

	}

(Tested with Typo3 version 10, but works also with Typo3 version 11 according to Simon Köhler)

You better clear every cache you can (at least composer dumpautoload) after changing classmap.

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