Ryan Brodie
Ryan Brodie

Reputation: 6620

Effective image resizing using PHP

I learn't how to resize images in PHP using a 9Lessons tutorial. Instead of storing these resized files on my web server where bandwidth is expensive I want to upload them to my CDN, a bucket on S3, using the S3 Class.

Heres my code (I've removed all error checking and file handling, please don't comment that it can only handle JPEG and the file can be any given size etc):

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

?>

When I run this script the S3 class pulls an error stating that $tmp is a resource and not a file. I understand that imagejpeg() is required to create the file, but how at this point can I upload it to S3? Will I need to create the image, store it locally, upload it to S3 and then delete? Or is there a better solution to my problem? Am I going about this completely the wrong way?

Upvotes: 0

Views: 774

Answers (1)

joas
joas

Reputation: 311

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

Upvotes: 1

Related Questions