【问题标题】:How to put PHP image resource into Amazon Web Services?如何将 PHP 图像资源放入 Amazon Web Services?
【发布时间】:2012-04-11 04:36:54
【问题描述】:

我目前正在构建一个 Zend Framework PHP Web 服务,它获取从 Android 手机上传的图像,调整其大小,然后将其放入 Amazon Web Services S3。

这是我的代码:

$img = $_FILES['image'];

    if(!$img)
    {
        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 =>
                zend_service_amazon_s3::S3_ACL_PUBLIC_READ
        );


        $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);

        imagedestroy($tmp);
        imagedestroy($srcImg);

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

我正在考虑一种将图像资源转换为流的方法,因此我可以使用 $s3->putFileStream 或 putObject 方法,但是我找不到有效的方法。

有什么想法吗??

【问题讨论】:

    标签: php zend-framework amazon-s3 gd


    【解决方案1】:

    以下是在不写入文件的情况下将图像放入变量的方法:

    ob_start();
    imagepng($image);
    $image_data = ob_get_contents();
    ob_end_clean();
    

    如果变量中有文件内容,则可以使用 putObject。这是我们使用 file_get_contents 的示例。请注意,我们正在从 Zend 配置文件中获取所有 S3 路径。

    $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));
        }
    

    【讨论】:

      猜你喜欢
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多