【问题标题】:Effective image resizing using PHP使用 PHP 有效地调整图像大小
【发布时间】:2012-08-28 11:28:56
【问题描述】:

我不知道如何使用 9Lessons tutorial 在 PHP 中调整图像大小。我不想将这些调整大小的文件存储在带宽昂贵的网络服务器上,而是使用 S3 类将它们上传到我的 CDN,即 S3 上的存储桶。

这是我的代码(我已删除所有错误检查和文件处理,请不要评论它只能处理 JPEG 并且文件可以是任何给定大小等):

<?php

if($_FILES["file"]["name"]) {

    $filename = stripslashes($_FILES['file']['name']);
    $uploadedfile = $_FILES['file']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);

    list($width,$height)=getimagesize($uploadedfile);
    $newwidth=200;
    $newheight=($height/$width)*$newwidth;
    $tmp=imagecreatetruecolor($newwidth,$newheight);

    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

    $filename = "small/".time().'.'.trim($_FILES['file']['name']);

    if(imagejpeg($tmp,$filename,100)) {
        imagedestroy($src);
        imagedestroy($tmp);
    }

    require('/path/to/S3.php');  

    if (!defined('awsAccessKey')) define('awsAccessKey', '');  
    if (!defined('awsSecretKey')) define('awsSecretKey', '');  

    $s3 = new S3(awsAccessKey, awsSecretKey);

    $put = S3::putObject(
        S3::inputFile($tmp),
        "bucket",
        $uploadFilename,
        S3::ACL_PUBLIC_READ,
        array(),
        array(
            "Cache-Control" => "max-age=315360000",
            "Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years"))
        )
    );
    var_dump($put);
}

?>

当我运行此脚本时,S3 类会显示一个错误,指出 $tmp 是资源而不是文件。我知道创建文件需要imagejpeg(),但此时我如何将其上传到 S3?我是否需要创建图像、将其存储在本地、将其上传到 S3 然后删除?或者我的问题有更好的解决方案吗?我是不是完全走错了路?

【问题讨论】:

    标签: php image file-upload amazon-s3


    【解决方案1】:
    $put = S3::putObject(
        S3::inputFile($filename), //<- Here changes $tmp for $filename
        "bucket",
        $uploadFilename,
        S3::ACL_PUBLIC_READ,
        array(),
        array(
            "Cache-Control" => "max-age=315360000",
            "Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years"))
        )
    

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2011-11-25
      • 2012-01-09
      相关资源
      最近更新 更多