Issue Task Closed

#107290Add an API-Feature to \TYPO3\CMS\Core\Resource\Processing\LocalCropScaleMaskHelper

C. Gogolin 08/14/25, 19:22 updated 11/11/26, 13:37

Description

Hi

The LocalCropScaleMaskHelper class contains a lot of smart logic that I’d like to use in my extension.

Unfortunately, I’m missing one small detail in LocalCropScaleMaskHelper. It uses the GraphicalFunctions#resize(…) method but doesn’t utilize the last parameter: $forceCreation. Normally that’s fine, but in my case it’s not, because my extension always needs a result, not just sometimes.

That’s why I extended the helper and LocalImageProcessor. My LocalImageProcessor now uses a subclassed helper that copies and slightly adjusts the most comprehensive method from the original class.

However, this isn’t elegant in the long run, because I always have to keep an eye on the original helper.

So here’s my proposal: (An optional constructor parameter controls $forceCreation)

<?php

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Core\Resource\Processing;

use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Imaging\GraphicalFunctions;
use TYPO3\CMS\Core\Imaging\ImageProcessingInstructions;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Helper class to locally perform a crop/scale/mask task with the TYPO3 image processing classes.
 */
class LocalCropScaleMaskHelper 
{
    public function __construct(private readonly bool $forceCreation = false)
    {
    }

    /**
     * This method actually does the processing of files locally
     *
     * Takes the original file (for remote storages this will be fetched from the remote server),
     * does the IM magic on the local server by creating a temporary typo3temp/ file,
     * copies the typo3temp/ file to the processing folder of the target storage and
     * removes the typo3temp/ file.
     *
     * The returned array has the following structure:
     *   width => 100
     *   height => 200
     *   filePath => /some/path
     *
     * If filePath isn't set but width and height are the original file is used as ProcessedFile
     * with the returned width and height. This is for example useful for SVG images.
     *
     * @param TaskInterface $task
     * @return array|null
     */
    public function process(TaskInterface $task)
    {
        return $this->processWithLocalFile($task, $task->getSourceFile()->getForLocalProcessing(false));
    }

    /**
     * Does the heavy lifting prescribed in processTask()
     * except that the processing can be performed on any given local image
     */
    public function processWithLocalFile(TaskInterface $task, string $originalFileName): ?array
    {
        $result = null;
        $targetFile = $task->getTargetFile();
        $targetFileExtension = $task->getTargetFileExtension();

        $imageOperations = GeneralUtility::makeInstance(GraphicalFunctions::class);

        $configuration = $targetFile->getProcessingConfiguration();
        $configuration['additionalParameters'] ??= '';

        // Normal situation (no masking) - just scale the image
        if (!is_array($configuration['maskImages'] ?? null)) {
            // the result info is an array with 0=width,1=height,2=extension,3=filename
            $result = $imageOperations->resize(
                $originalFileName,
                $targetFileExtension,
                $configuration['width'] ?? '',
                $configuration['height'] ?? '',
                $configuration['additionalParameters'],
                $configuration,
                $this->forceCreation
            );
        } else {
            $temporaryFileName = $this->getFilenameForImageCropScaleMask($task);
            $maskImage = $configuration['maskImages']['maskImage'] ?? null;
            $maskBackgroundImage = $configuration['maskImages']['backgroundImage'];
            if ($maskImage instanceof FileInterface && $maskBackgroundImage instanceof FileInterface) {
                // This converts the original image to a temporary PNG file during all steps of the masking process
                $tempFileInfo = $imageOperations->resize(
                    $originalFileName,
                    'png',
                    $configuration['width'] ?? '',
                    $configuration['height'] ?? '',
                    $configuration['additionalParameters'],
                    $configuration,
                    $this->forceCreation
                );
                if ($tempFileInfo !== null) {
                    // Scaling
                    $command = '-geometry ' . $tempFileInfo->getWidth() . 'x' . $tempFileInfo->getHeight() . '!';
                    $imageOperations->mask(
                        $tempFileInfo->getRealPath(),
                        $temporaryFileName,
                        $maskImage->getForLocalProcessing(),
                        $maskBackgroundImage->getForLocalProcessing(),
                        $command,
                        $configuration
                    );
                    $maskBottomImage = $configuration['maskImages']['maskBottomImage'] ?? null;
                    $maskBottomImageMask = $configuration['maskImages']['maskBottomImageMask'] ?? null;
                    if ($maskBottomImage instanceof FileInterface && $maskBottomImageMask instanceof FileInterface) {
                        // Uses the temporary PNG file from the previous step and applies another mask
                        $imageOperations->mask(
                            $temporaryFileName,
                            $temporaryFileName,
                            $maskBottomImage->getForLocalProcessing(),
                            $maskBottomImageMask->getForLocalProcessing(),
                            $command,
                            $configuration
                        );
                    }
                }
                $result = $tempFileInfo;
            }
        }

        // check if the processing really generated a new file (scaled and/or cropped)
        if ($result !== null) {
            // The file processing yielded a different file extension than we anticipated. Most likely because
            // the processing service found out a file type needed to use fallback storage. In this case, we
            // append the actually received file extension to our file to be stored, which will also hint at
            // a failed conversion, like some-file.avif.jpg. Otherwise use the same file extension. This is
            // evaluated for persistence in @see LocalImageProcessor->processTaskWithLocalFile().
            $remapProcessedTargetFileExtension = ($targetFileExtension !== $result->getExtension())
                // Remap to correct image type extension.
                ? $result->getExtension()
                // No file extension remap required.
                : null;
            // @todo: realpath handling should be revisited, they may produce issues
            //        with open_basedir restrictions and/or lockRootPath.
            if ($result->getRealPath() !== realpath($originalFileName)) {
                $result = [
                    'width' => $result->getWidth(),
                    'height' => $result->getHeight(),
                    'filePath' => $result->getRealPath(),
                    'remapProcessedTargetFileExtension' => $remapProcessedTargetFileExtension,
                ];
            } else {
                // No file was generated
                $result = null;
            }
        }

        // If noScale option is applied, we need to reset the width and height to ensure the scaled values
        // are used for the generated image tag even if the image itself is not scaled. This is needed, as
        // the result is discarded due to the fact that the original image is used.
        // @see https://forge.typo3.org/issues/100972
        // Note: This should only happen if no image has been generated ($result === null).
        if ($result === null && ($configuration['noScale'] ?? false)) {
            $configuration = $task->getConfiguration();
            $localProcessedFile = $task->getSourceFile()->getForLocalProcessing(false);
            $imageDimensions = $imageOperations->getImageDimensions($localProcessedFile, true);
            $imageScaleInfo = ImageProcessingInstructions::fromCropScaleValues(
                $imageDimensions->getWidth(),
                $imageDimensions->getHeight(),
                $configuration['width'] ?? '',
                $configuration['height'] ?? '',
                $configuration
            );
            $targetFile->updateProperties([
                'width' => $imageScaleInfo->width,
                'height' => $imageScaleInfo->height,
            ]);
        }

        return $result;
    }

    /**
     * Returns the filename for a cropped/scaled/masked file which will be put in typo3temp for the time being.
     */
    protected function getFilenameForImageCropScaleMask(TaskInterface $task): string
    {
        $targetFileExtension = $task->getTargetFileExtension();
        return Environment::getPublicPath() . '/typo3temp/' . $task->getTargetFile()->generateProcessedFileNameWithoutExtension() . '.' . ltrim(trim($targetFileExtension), '.');
    }
}

Reviews 5

History 755

Show 530 earlier messages
  1. Garvin Hicking commented and changed status New Needs Feedback <span data-processor="relativetime" data-value="2025-08-14T20:16:07+00:00" > 08/14/25, 20:16 </span>

    Hi!

    Thanks for contributing! Would you like to propose this as a patch on gerrit (review.typo3.org, see contribution guide on https://docs.typo3.org/core-contribution)? That would make code review and voting and testing easier. :)

  2. C. Gogolin commented <span data-processor="relativetime" data-value="2025-08-15T18:15:11+00:00" > 08/15/25, 18:15 </span>

    Garvin Hicking wrote in #note-1:
    > Hi!
    >
    > Thanks for contributing! Would you like to propose this as a patch on gerrit (review.typo3.org, see contribution guide on https://docs.typo3.org/core-contribution)? That would make code review and voting and testing easier. :)

    Can you help me?

    git push origin HEAD:refs/for/main
    docmcfly@review.typo3.org: Permission denied (publickey).
    fatal: Konnte nicht vom Remote-Repository lesen.

    Bitte stellen Sie sicher, dass die korrekten Zugriffsberechtigungen bestehen
    und das Repository existiert.

  3. Garvin Hicking commented <span data-processor="relativetime" data-value="2025-08-15T19:28:19+00:00" > 08/15/25, 19:28 </span>

    Hey, sure. Are you on slack? Send me a DM (supergarv).

    Did you upload your public key in the Gerrit (review.typo3.org) interface? The contrib guide should have a screenshot.

  4. C. Gogolin commented <span data-processor="relativetime" data-value="2025-08-16T13:49:13+00:00" > 08/16/25, 13:49 </span>

    I just signed into Slack and now remember why I wanted to leave it.

    Sending a message to supergarv doesn’t seem possible—I’d have to invite you somehow, and that requires an email address… <— OMG, that’s annoying.

    Yes, I uploaded my public key to Gerrit and it’s shown as valid. To be safe, I adjusted the config:

    Host review.typo3.org    
      HostName review.typo3.org
      User docmcfly
      Port 22
      IdentityFile /home/clemens/.ssh/keys/typo3
      Compression yes

    But still:

    $ ssh review.typo3.org
    docmcfly@review.typo3.org: Permission denied (publickey).

    Is it really this complicated to submit a change request to Typo3?

  5. Garvin Hicking commented <span data-processor="relativetime" data-value="2025-08-16T18:12:45+00:00" > 08/16/25, 18:12 </span>

    Did you login to the typo3 slack (https://typo3.org/community/meet/chat-slack)?! If you’re in there you don’t need any invitations to send DMs.

    In that DM you can send me screenshots of your gerrit UI that shows the public key. Which key type did you use? Try ed25519.?

    Also, your username is the username you use on my.typo3.org right?

    Also, please be patient. After all I’m trying to help here. :-)

    You can also send a github PR that will get converted to gerrit. This way you will probably not get feedback on gerrit and submitting changes to a patch will not be possible.

  6. Gerrit Code Review pushed patch set 1 for main to change 90428 status Needs Feedback Under Review <span data-processor="relativetime" data-value="2025-08-17T15:58:28+00:00" > 08/17/25, 15:58 </span>

  1. Garvin Hicking commented and changed status Under Review Closed <span data-processor="relativetime" data-value="2026-11-11T13:37:52+00:00" > 11/11/26, 13:37 </span>

    Abandoning, I’m afraid we couldn’t move this forward – closing for housekeeping. Can be restored if work shall be put up again.