resize image, compress, and save to amazon s3 in php

To resize and compress an image in PHP, you can use the GD library. Here's an example:

main.php
// Get the uploaded file
$file = $_FILES['image'];

// Set the maximum size for the image
$max_size = 800;

// Set the compression level
$compression_level = 60;

// Create an image object from the uploaded file
$image = imagecreatefromstring(file_get_contents($file['tmp_name']));

// Get the current dimensions of the image
$width = imagesx($image);
$height = imagesy($image);

// Calculate the new dimensions maintaining the aspect ratio
if ($width > $height) {
    $new_width = $max_size;
    $new_height = floor($height * ($max_size / $width));
} else {
    $new_height = $max_size;
    $new_width = floor($width * ($max_size / $height));
}

// Create a new image with the new dimensions
$new_image = imagecreatetruecolor($new_width, $new_height);

// Resize the original image to the new dimensions
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Save the compressed image to a file
imagejpeg($new_image, 'compressed.jpg', $compression_level);

// Upload the compressed image to Amazon S3
require 'aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$key = 'your key';
$secret = 'your secret';
$bucket = 'your bucket';

$s3 = new S3Client([
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' => [
        'key' => $key,
        'secret' => $secret,
    ],
]);

try {
    $result = $s3->putObject([
        'Bucket' => $bucket,
        'Key' => 'compressed.jpg',
        'SourceFile' => 'compressed.jpg',
        'ACL' => 'public-read',
    ]);
    echo 'Image uploaded to Amazon S3';
} catch (AwsException $e) {
    echo $e->getMessage();
}
1643 chars
64 lines

In this example, we first get the uploaded file and define the maximum size and compression level we want for the image. We then create a new image with the new dimensions and resize the original image to fit into this new one. Finally, we compress and save this new image to a file with the imagejpeg() function and upload it to Amazon S3 with the AWS SDK for PHP.

gistlibby LogSnag