简体   繁体   中英

How to upload image to AWS S3 in PHP from memory?

So I currently have an upload system working using AWS S3 to upload images.

Here's the code:

//Upload image to S3
$s3 = Aws\S3\S3Client::factory(array('key' => /*mykey*/, 'secret' => /*myskey*/,));

try {
    $s3->putObject(array(
        'Bucket' => "bucketname",
        'Key'    => $file_name,
        'Body'   => fopen(/*filelocation*/, 'r+')
    ));
} catch(Exception $e) {
    //Error
}

This image can be a jpeg or png, and I want to convert it to a png before uploading. To do this I use:

//This is simplified, please don't warn about transparency, etc.
$image = imagecreatetruecolor($width, $height);
imagecopyresampled($image, $source, 0, 0, 0, 0, etc.);

So I have this $image object in memory.

I want to upload this to S3 without having to save it locally, upload it and then delete it locally; this extra step seems pointless. But I can't work out how to upload this $image object directly.

Any ideas how this would be done? I'd assumed fopen() would create an object of a similar type to imagecreatetruecolor(), but I've tried passing the $image object in and it doesn't work - whereas it does if I open an image locally with fopen().

You can capture the content of a GD image resource using output buffering :

ob_start();
imagepng($image);
$pngdata = ob_get_clean();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM