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

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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

回答1:

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

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!