我试图让我的用户将照片上传到我的网络服务器,制作缩略图,然后将其上传到亚马逊s3服务器。
出于某种原因,在尝试上传6mb图像时,服务器会记录:
Allowed memory size of 67108864 bytes exhausted (tried to allocate 17280 bytes)
为什么我的代码占用了6MB的大量内存?这是正常的吗?也许我需要知道一种在我的代码中某处清除内存的方法,然后再转到下一部分?
我知道我可以增加我的记忆,但这似乎是一种解决这个问题的非健康方法。我正在寻找一种使用更少内存的不同方法。
这是我在html页面上使用jquery上传时使用的upload.php文件。 html页面通过ajax调用upload.php。
upload.php的:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 8000 * 1024; // max file size (8MB)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( @is_uploaded_file($_FILES['image']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
// unique file path
$path = $path . *******. '.' .$ext;
$secret = ********;
$imgname = 'useralbums/'.$wedding_id.'/'.$wedding_id.'_'******'.'.$ext;
$thumbname = 'useralbums/'.$wedding_id.'/'.$wedding_id.'_'******'_thumb.'.$ext;
$tempthumb = 'temp.'.$ext;
// move uploaded file from temp to uploads directory
make_thumb($_FILES['image']['tmp_name'], $tempthumb, 250, $ext);
$status = array();
$binary = file_get_contents($_FILES['image']['tmp_name'], true);
$status['img'] = saveFileInS3($imgname, $binary);
$binary = file_get_contents($tempthumb, true);
$status['thumb'] = saveFileInS3($thumbname, $binary);
$category = 'Reception'; // TO DO: Catch categories
if (add_wedding_photos($status['img'],$status['thumb'],$wedding_id, $category)) { $status['db'] = 'OK'; }
unlink($tempthumb);
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
echo json_encode(array('status' => $status));
function make_thumb($src, $dest, $desired_width, $ext) {
if ($ext == 'jpg' || $ext == 'jpeg') {
$source_image = imagecreatefromjpeg($src);
}
if ($ext == 'png') {
$source_image = imagecreatefrompng($src);
}
if ($ext == 'gif') {
$source_image = imagecreatefromgif($src);
}
/* read the source image */
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
$desired_height = 250;
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
if ($ext == 'jpg' || $ext == 'jpeg') {
imagejpeg($virtual_image, $dest);
}
if ($ext == 'png') {
imagepng($virtual_image, $dest);
}
if ($ext == 'gif') {
imagegif($virtual_image, $dest);
}
}
谢谢!