[953 Aufrufe]

5.12 Hooks: images

In diesem Abschnitt beschäftigen wir uns mit den Hooks für die Bilder.

Hook: executeResize

Der executeResize Hook wird aufgerufen, wenn Contao die Größe eines Bilds ändert.

Registrierung

# /src/Ctocb/Example/Resources/config/services.yml
services:

  # Hooks
  Ctocb\Example\Classes\Contao\Hooks\ExampleHook:
    public: true
    tags:
      - { name: contao.hook, hook: executeResize, method: handleHook, priority: 1024 }

Klasse

<?php

namespace Ctocb\Example\Classes\Contao\Hooks;

use Contao\Image;

class ExampleHook {

    public function handleHook(Image $image): ?string
    {
        if (/*...*/) {
            // Do something and return the path to the resized image

            return $pathToResizedImage;
        }

        return null;
    }
}

Parameter:

Parameter Typ Beschreibung
$image \Contao\Image Instanz der Images-Objekts

Rückgabewert:

Typ Beschreibung
string|null null oder der Pfad zum erzeugten Bild

Referenz im Contao Core: \Contao\LegacyResizer.php#L79-L87 und \Contao\Image.php#L429-L443

Hook: getImage

Der getImage Hook wird aufgerufen, wenn ein Vorschaubild erzeugt wird.

Registrierung

# /src/Ctocb/Example/Resources/config/services.yml
services:

  # Hooks
  Ctocb\Example\Classes\Contao\Hooks\ExampleHook:
    public: true
    tags:
      - { name: contao.hook, hook: getImage, method: handleHook, priority: 1024 }

Klasse

<?php

namespace Ctocb\Example\Classes\Contao\Hooks;

use Contao\Image;
use Contao\File;

class ExampleHook {

    public function handleHook(
        string $originalPath, 
        int $width, 
        int $height, 
        string $mode, 
        string $cacheName, 
        File $file, 
        string $targetPath, 
        Image $imageObject
    ): ?string {
        // Return the path to a custom image
        if (/* ... */) {
            return $newImagePath;
        }

        return null;
    }
}

Parameter:

Parameter Typ Beschreibung
$originalPath string Pfad zum Bild
$width int Breite des Bilds
$height int Höhe des Bilds
$mode string Art der Größenänderung ("mitte|mitte", "Proportional", ...)
$cacheName string Dateiname des zwischengespeicherten Bilds
$file \Contao\File Instanz des Datei-Objekts
$targetPath string Zeipfad für das Bild, ist meist null
$imageObject \Contao\Image Instanz der Images-Objekts

Rückgabewert:

Typ Beschreibung
string|false false oder der Pfad zum Bild

Referenz im Contao Core: \Contao\CoreBundle\Image\LegacyResizer#L100-L114