aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/StockImages/Scaler.php
blob: 32f6c7aa92d98174fecabe8754723267ae9f0369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace Studip\StockImages;

final class Scaler
{
    /**
     * @param \StockImage $stockImage
     */
    public function __invoke(\StockImage $stockImage): void
    {
        foreach (\StockImage::sizes() as $name => $width) {
            if ($name !== \StockImage::SIZE_ORIGINAL) {
                $this->scaleToWidth($stockImage, $name, $width);
            }
        }
    }

    private function scaleToWidth(\StockImage $stockImage, string $sizeName, int $targetWidth): bool
    {
        $image = $this->createImage($stockImage);
        $width = imagesx($image);
        if ($width < $targetWidth) {
            return false;
        }

        $scaledImage = imagescale($image, $targetWidth);
        imagedestroy($image);

        return $this->storeImage($stockImage, $scaledImage, $sizeName);
    }

    /**
     * @return resource the \GDImage created from the original image file
     */
    private function createImage(\StockImage $stockImage)
    {
        $type = $stockImage->mime_type;
        $lookup = [
            'image/gif' => 'imagecreatefromgif',
            'image/jpeg' => 'imagecreatefromjpeg',
            'image/png' => 'imagecreatefrompng',
            'image/webp' => 'imagecreatefromwebp',
        ];
        if (!isset($lookup[$type])) {
            throw new \RuntimeException(_('Unsupported image type.'));
        }

        return $lookup[$type]($stockImage->getPath());
    }

    /**
     * @param resource $image the scaled image
     */
    private function storeImage(\StockImage $stockImage, $image, string $sizeName): bool
    {
        $type = $stockImage->mime_type;
        $lookup = [
            'image/gif' => 'imagegif',
            'image/jpeg' => 'imagejpeg',
            'image/png' => 'imagepng',
            'image/webp' => 'imagewebp',
        ];
        if (!isset($lookup[$type])) {
            throw new \RuntimeException(_('Unsupported image type.'));
        }

        return $lookup[$type]($image, $stockImage->getPath($sizeName));
    }
}