PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How to upload image to AWS S3 in PHP from memory?

 May 06, 2022     amazon-s3, amazon-web-services, file-upload, image, php     No comments   

Issue

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().


Solution

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

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


Answered By - user149341
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing