resize image, compress, and save to amazon s3 using spatie media library in php

You can use the Spatie Media Library package for PHP to resize and compress images before saving them to Amazon S3. Here's an example code block:

main.php
use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\Conversion\Conversion;
use Spatie\Image\Image;
use Spatie\Image\Manipulations;

// Get the media object
$media = Media::findOrFail($mediaId);

// Create a new conversion
Conversion::create('thumb')
    ->setManipulations(
        function (Manipulations $manipulations) {
            // Set the size and quality of the image
            $manipulations->fit(Manipulations::FIT_CROP, 100, 100)
                ->quality(70);
        }
    )
    ->register();

// Perform the conversion
$convertedImage = $media->getConversion('thumb');

// Get the stream of the converted image
$imageStream = Image::load($convertedImage->getPath())->stream();

// Save to Amazon S3
$fileName = $convertedImage->getName();
$s3 = Storage::disk('s3');
$s3->put($fileName, $imageStream);
828 chars
30 lines

In this example, we first get the media object using its ID. We then create a new conversion named thumb that resizes the image to 100x100 pixels and sets its quality to 70.

We then perform the conversion on the media object using getConversion() and get the stream of the converted image using Image::load()->stream(). Finally, we save the image to Amazon S3 using the put() method of the s3 disk of Laravel's Storage facade.

gistlibby LogSnag