I am working on a Laravel application and at some point, when I allow users to upload their own images for different purposes, I want to generate resized previews for these images.
I am uploading all user content to Amazon S3 and the first thing I did about resizing image is uploading the original image, then went through a foreach
, resized the image and re-uploaded it to S3.
As you can image, having 4 sizes for each image dramatically increases the upload time and is a performance concern for me.
Here is a code snippet that I use in my upload
function:
$storageDriver = Storage::disk('cloud-storage')->getDriver();
$parentSuccess = $storageDriver->put("/$parentId", file_get_contents($file), [
'visibility' => 'public',
'ACL' => 'public-read',
'ContentType' => $contentType,
]);
$ratio = $imageSize[0] / $imageSize[1];
foreach (self::IMAGE_SIZES as $size) {
if ($size > $imageSize[0] || ($size / $ratio) > $imageSize[1]) {
continue;
}
$id = DB::table('storage')->insertGetId([
'content_type' => $contentType,
'parent_id' => $parentId,
'image_width' => $size,
'image_height' => intval($size / $ratio),
]);
$image = Image::make($file)->encode('jpg');
$image->resize($size, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$image->save();
$success = $storageDriver->put("/$id", (string)$image, [
'visibility' => 'public',
'ACL' => 'public-read',
'ContentType' => 'image/jpeg',
]);
if (!$success) {
return null;
}
}
(I know there is a lot of code not included, but it's not relevant).
What method would you choose for handling this in a more efficient way?