所以我想调整我的图片上传,这样,如果图像是在35KB压缩它,但它似乎没有工作,不要想我这样做是正确,因为它总是给我错误 “文件大小太大了!最大值是35kb,尝试使用一些更多的压缩,或找到另一个图像。”压缩上传的图片是否过大
这里是我的代码:
function article_top_image($article_id)
{
global $db, $config;
if (isset($_FILES['new_image']) && $_FILES['new_image']['error'] == 0)
{
if ([email protected]($_FILES['new_image']['tmp_name'], 'r'))
{
$this->error_message = "Could not find image, did you select one to upload?";
return false;
}
else
{
// check the dimensions
list($width, $height, $type, $attr) = getimagesize($_FILES['new_image']['tmp_name']);
// check if its too big
if ($_FILES['new_image']['size'] > 35900)
{
// compress it to see if we can make it smaller
imagejpeg($_FILES['new_image']['tmp_name'], $_FILES['new_image']['tmp_name'], 50);
// check again
if ($_FILES['new_image']['size'] > 35900)
{
$this->error_message = 'File size too big! The max is 35kb, try to use some more compression on it, or find another image.';
return false;
}
}
else if ($width > $config['article_image_max_width'] || $height > $config['article_image_max_height'])
{
$this->error_message = 'Too big!';
return false;
}
// this will make sure it is an image file, if it cant get an image size then its not an image
else if (!getimagesize($_FILES['new_image']['tmp_name']))
{
$this->error_message = 'Not an image!';
return false;
}
}
// see if they currently have an avatar set
$db->sqlquery("SELECT `article_top_image` FROM `articles` WHERE `article_id` = ?", array($article_id));
$image = $db->fetch();
// give the image a random file name
$imagename = rand() . 'id' . $article_id . '.jpg';
// the actual image
$source = $_FILES['new_image']['tmp_name'];
// where to upload to
$target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename;
if (move_uploaded_file($source, $target))
{
// remove old avatar
if ($image['article_top_image'] == 1)
{
unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/articles/topimages/' . $image['article_top_image_filename']);
}
$db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id));
return true;
}
else
{
$this->error_message = 'Could not upload file!';
return false;
}
return true;
}
}
不知怎的,我不认为'$ _FILES [“new_image”] [“大小”]'将与新的图像尺寸神奇地更新你重新保存图像之后。除此之外,不一定能保证图像可以一次压缩到35 KB,而不会损失太多质量。 – DCoder 2013-04-07 10:05:06
质量不是什么大问题,因为它会是一个非常小的图像。 – NaughtySquid 2013-04-07 10:08:47