summaryrefslogtreecommitdiff
path: root/src/images.php
blob: fea18254846e6b112d13285ace3b2098f5fcc8e3 (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
<?php
function resize_image(string $src_path, string $dst_path, int $max_width, int $max_height): string|null
{
    if ($src_path == "" || !getimagesize($src_path)) {
        return json_encode([
            "status_code" => 400,
            "message" => "Not an image",
            "data" => null
        ]);
    }

    $imagick = new Imagick();

    $imagick->readImage($src_path);
    $format = strtolower($imagick->getImageFormat());

    if ($imagick->getNumberImages() > 1) {
        $imagick = $imagick->coalesceImages();

        foreach ($imagick as $frame) {
            $width = $frame->getImageWidth();
            $height = $frame->getImageHeight();
            $ratio = min($max_width / $width, $max_height / $height);
            $new_width = (int) ($width * $ratio);
            $new_height = (int) ($height * $ratio);

            $frame->resizeImage($new_width, $new_height, Imagick::FILTER_TRIANGLE, 1);
            $frame->setImagePage($new_width, $new_height, 0, 0);
        }

        $imagick = $imagick->deconstructImages();
        $imagick->writeImages("$dst_path.$format", true);
    } else {
        $width = $imagick->getImageWidth();
        $height = $imagick->getImageHeight();
        $ratio = min($max_width / $width, $max_height / $height);
        $new_width = (int) ($width * $ratio);
        $new_height = (int) ($height * $ratio);

        $imagick->resizeImage($new_width, $new_height, Imagick::FILTER_TRIANGLE, 1);
        $imagick->writeImage("$dst_path.$format");
    }

    $imagick->clear();
    $imagick->destroy();

    return null;
}

function get_mime_and_ext(string $src_path): array|null
{
    if ($src_path == "") {
        return null;
    }

    $imagick = new Imagick();

    $imagick->readImage($src_path);
    $ext = strtolower($imagick->getImageFormat());
    $mime = $imagick->getImageMimeType();

    $imagick->clear();
    $imagick->destroy();

    return [$mime, $ext];
}