How do I host a PHP image resource on Amazon Web Services?

I am currently creating a Zend Framework PHP web service that takes an image downloaded from an Android phone, resizes it and puts it into Amazon Web Services S3 web services.

Here are my codes:

$img = $_FILES['image'];

        return null;

    if((($img['type'] == 'image/gif') ||
            ($img['type'] == 'image/jpeg') ||
            ($img['type'] == 'image/png')) &&
            ($img['size'] < 1048576))
        if($img['error'] >0)
            throw new Exception("image contain error ");

        $size24 = 24;

        //obtain the auth settings
        $bootstrap = $this->getInvokeArg('bootstrap');
        $awsConfigs = $bootstrap->getOption('aws');

        $s3 = new Zend_Service_Amazon_S3($awsConfigs['appkey'], $awsConfigs['secretkey']);

        $bucketName = 'item';
        $folderName = 'image';

        $perms = array(
                Zend_Service_Amazon_S3::S3_ACL_HEADER =>

        $name =  $bucketName.'/'. $folderName .'/'. uniqid() .'_'. Zend_Date::now()->toString('yyyyMMdd');
        $smallPath = $name . '_32.png';

        //resize and upload 24x24 image
        $srcImg = imagecreatefrompng($img['tmp_name']);
        $tmp = imagecreatetruecolor($size24, $size24);
        list($oriWidth, $oriHeight) = getimagesize($img['tmp_name']);
        imagecopyresampled($tmp, $srcImg, 0, 0, 0, 0, $size24, $size24, $oriWidth, $oriHeight);
        //not working
                    imagepng($tmp, "tmp_32.png")
        $smallret = $s3->putFile("tmp_32.png", $smallPath, $perms);


        throw new Exception("image size/format not qualified.");


I think there is a way to convert the image resource to a stream, so I can use the $ s3-> putFileStream or putObject method, but I cannot find the correct path.

Any idea?


source to share

1 answer

This is how you get the image into a variable without writing to a file:

$image_data = ob_get_contents();


If you have the content of the file in a variable, you can use putObject. Here's our example where we are using file_get_contents. Note that we are getting all S3 paths from our Zend config file.

$image_data = file_get_contents(<filename>);
$aws_accesskey = Zend_Registry::get('config')->amazon->accesskey;
$aws_secret = Zend_Registry::get('config')->amazon->secret;
$s3 = new Zend_Service_Amazon_S3($aws_accesskey, $aws_secret);
$image_path = Zend_Registry::get('config')->amazon->s3->assetsbucket . "/images/$filename";
$s3->putObject($image_path, $image_data, array(Zend_Service_Amazon_S3::S3_ACL_HEADER => Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ));




All Articles