I am using S3 to store images and I am resizing and compressing images before it gets uploaded using PHP. I’m using this class for storing the images to an S3 bucket – http://undesigned.org.za/2007/10/22/amazon-s3-php-class
This all works fine if I’m not doing any file processing before the file is uploaded because it reads the file upload from the $_FILES array.
The problem is I am resizing and compressing the image before storing to the S3 bucket. So I’m no longer able to read from the $_FILES array.
The functions for resizing:
public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $option);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($option == 'crop') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}
The script I am using to store the file after resizing and compressing to a local directory:
public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
$extension = strrchr($savePath, '.');
$extension = strtolower($extension);
switch($extension)
{
case '.jpg':
case '.jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;
case '.gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;
case '.png':
// *** Scale quality from 0-100 to 0-9
$scaleQuality = round(($imageQuality/100) * 9);
// *** Invert quality setting as 0 is best, not 9
$invertScaleQuality = 9 - $scaleQuality;
if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;
// ... etc
default:
// *** No extension - No save.
break;
}
imagedestroy($this->imageResized);
}
with this PHP code to invoke it:
$resizeObj = new resize("$images_dir/$filename");
$resizeObj -> resizeImage($thumbnail_width, $thumbnail_height, 'crop');
$resizeObj -> saveImage($images_dir."/tb_".$filename, 90);
How do I modify the code above so I can pass it through this function:
$s3->putObjectFile($thefile, "s3bucket", $s3directory, S3::ACL_PUBLIC_READ)
Used the copy PHP function to save to a temporary directory and then used the S3 function to read from the directory. Once the S3 upload is complete, the file is deleted from the temporary directory using the unlink function.