PHP - 我正在使用此代码上传图片文件,但我不知道如何减少图片文件大小,但应保持质量。
$todir = 'members/'.$_SESSION[' valid_user '].'/';
$RandomNum = rand(0, 9999999999);
$info = explode('.', strtolower( $_FILES['Image']['name']) ); // whats the extension of the file
if(move_uploaded_file( $_FILES['Image']['tmp_name'], $todir . basename($_FILES['Image']['name']-$RandomNum) ) )
{
$handle= 'members/'.$_SESSION[' valid_user '].'/'.basename($_FILES['Image']['name']-$RandomNum);
echo 'uploaded';
}
答案 0 :(得分:1)
您是否尝试使用ImageMagick将图像缩小到更合适的尺寸? (http://jsfiddle.net/greggy_coding/uvb4qp2m/11/)
答案 1 :(得分:-1)
$name = "";
$type = "";
$size = "";
$error = "";
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
if ($_POST) {
if ($_FILES["file"]["error"] > 0){
$error = $_FILES["file"]["error"];
} else if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")){
$url = $_FILES["file"]["name"];
$filename = compress_image($_FILES["file"]["tmp_name"], $url, 30);
$buffer = file_get_contents($url);
}else {
$error = "Uploaded image should be jpg or gif or png";
}
}
<html>
<head>
<title>Php code compress the image</title>
</head>
<body>
<div class="message">
<?php if($_POST){ if ($error) { ?>
<label class="error"><?php echo $error; ?></label>
<?php } } ?>
</div>
<legend>Upload Image:</legend>
<form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
<label>Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" name="submit" id="submit" class="submit btn-success"/>
</form>
</body>
</html>