This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

josh70520
josh70520

I have an image path and am trying to use the thumbnail generator to generate a cropped version of it.

This is the function I've cobbled together so far, and it kind of works:

function getThumbnail(string $image, int $width, int $height) {
    $imagePath = storage_path("app/media/$image");

    $file = new \System\Models\File;

    $file->fromFile($imagePath);

    return $file->getThumb($width, $height, ['mode' => 'crop']);
}

$image = 'test1.png';

echo getThumbnail(200, 200, $image);

//returns
'https://example.co.uk/storage/app/uploads/public/620/3c5/a99/thumb__200_200_0_0_crop.png' //winner

The problem is that the new \System\Models\File is lacking an id. As such when you do conversions with the same width and height, it has a (weridly patchy) tendency to overwrite each other:

$images = [
    'test1.png',
    'test2.png',
    'test3.png',
    'test4.png',
    'test5.png',
];

foreach($images as $image) {
    echo getThumbnail(200, 200, $image);
}

// returns something like

'https://example.co.uk/storage/app/uploads/public/620/3c5/a99/thumb__200_200_0_0_crop.png' //good
'https://example.co.uk/storage/app/uploads/public/620/3c5/a9a/thumb__200_200_0_0_crop.png' //good
'https://example.co.uk/storage/app/uploads/public/620/3c5/a9a/thumb__200_200_0_0_crop.png' //repeats from here on out
'https://example.co.uk/storage/app/uploads/public/620/3c5/a9a/thumb__200_200_0_0_crop.png'
'https://example.co.uk/storage/app/uploads/public/620/3c5/a9a/thumb__200_200_0_0_crop.png'

I can shove a random id in that fixes the duplication issue:

function getThumbnail(string $image, int $width, int $height) {
    $imagePath = storage_path("app/media/$image");

    $file = new \System\Models\File;

    $file->id = mt_rand(1000000, 9999999);

    $file->fromFile($imagePath);

    return $file->getThumb($width, $height, ['mode' => 'crop']);
}

But this causes yet another issue, where the thumbnail is generated anew on each page load, which will bloat my storage folder something chronic in no time flat.

I was thinking of trying to come up with a way of converting a filepath into an integer, but then I figured that I must be going about this completely wrong in the first place, and that someone who hadn't started using October a week ago would know the proper way of doing this.

daftspunky

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.