php 上传时压缩图像文件大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1254083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compress image file size on upload?
提问by halocursed
I am uploading product screenshots to my website... I want to upload the original image as it is and also create a thumbnail for it, but after uploading both the files the filesize of the thumbnail created is a bit larger than expected. Is there any way I could reduce the filesize of the thumbnail without compromising much on the quality in php or by using Imagemagick( which I have no idea how to use but I'm willing to learn if needed)...
Below is the code I'm using to upload my files..
我正在将产品屏幕截图上传到我的网站...我想按原样上传原始图像并为其创建缩略图,但是在上传这两个文件后,创建的缩略图的文件大小比预期的要大一些。有什么方法可以减少缩略图的文件大小而不影响 php 中的质量或使用 Imagemagick(我不知道如何使用,但我愿意在需要时学习)......
下面是代码我用来上传我的文件..
<form action="<?php echo $_server['php-self']; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
<button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$tn = imagecreatetruecolor($width, $height) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ;
imagejpeg($tn, $save, 100) ;
$save = "images/sml_" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 130;
$diff = $width / $modwidth;
$modheight = 185;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
imagejpeg($tn, $save, 100) ;
echo "Large image: <img src='images/".$imagepath."'><br>";
echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
}
} ?>
Kindly point me in the right direction...Thanks
请指出我正确的方向......谢谢
回答by Paul Dixon
Don't pass 100 as the quality for imagejpeg()- anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.
不要通过 100 作为imagejpeg()的质量- 任何超过 90 的东西通常都是过大的,只会让您获得更大的 JPEG。对于缩略图,尝试 75 并向下工作,直到质量/大小权衡可以接受为止。
//try this
imagejpeg($tn, $save, 75) ;
回答by Kamlesh
Hello @halocursed I just try to compress using your code for different image type like png and gif than image comes black. So, I modify the block of code and good working for jpg, png.
您好@halocursed 我只是尝试使用您的代码压缩不同的图像类型,例如 png 和 gif,而不是图像变黑。所以,我修改了代码块,并为 jpg、png 做好了工作。
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
// print_r($_FILES); die;
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file);
$tn = imagecreatetruecolor($width, $height);
//$image = imagecreatefromjpeg($file);
$info = getimagesize($target);
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($file);
}elseif ($info['mime'] == 'image/gif'){
$image = imagecreatefromgif($file);
}elseif ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($file);
}
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($tn, $save, 60);
echo "Large image: ".$imagepath;
}
}
?>
回答by Marijan
It should be 60, it stands for 60 percent.
它应该是 60,它代表 60%。
Example: If you open an image in Photoshop and try save it for web and select jpg, you can see that by using 60 it's still under high quality, but lower file size. If you would like lower, with more degradation, meaning the colors are distorted more.
示例:如果您在 Photoshop 中打开图像并尝试将其保存为 Web 并选择 jpg,您可以看到使用 60 它仍然处于高质量状态,但文件大小较小。如果你想要更低,更多的退化,意味着颜色扭曲更多。
More than 60 does not give you anything better, only larger file size.
超过 60 不会给你任何更好的东西,只是更大的文件大小。
It's standard image optimization for web. Keep high quality but keep file size as low as possible.
这是网络的标准图像优化。保持高质量但保持文件大小尽可能小。
回答by Alix Axel
75 is the default quality setting, however you'll notice quality decrease considerably if you use it. 90 gives you a great image quality and reduces the file size in half, if you want to decrease the file size even more use 85 or 80 but nothing bellow that.
75 是默认的质量设置,但是如果您使用它,您会发现质量会大大降低。90 为您提供出色的图像质量并将文件大小减少一半,如果您想进一步减小文件大小,请使用 85 或 80,但不要低于此值。
回答by Pascal MARTIN
If using jpeg, using a quality between 75 and 85 is generally more than acceptable (and 100 takes way too much space, for a gain that is not that important, btw), at least for photos.
如果使用 jpeg,使用 75 到 85 之间的质量通常是可以接受的(100 占用太多空间,顺便说一句,增益并不那么重要),至少对于照片。
As a sidenote, if you are dealing with screenshots, using PNG might get you a better quality : jpeg degrades the images (it is quite OK for photos, but for screenshots, with fonts that are drawn by pixels, it can bring some not nice-looking effect)
作为旁注,如果您正在处理屏幕截图,使用 PNG 可能会让您获得更好的质量:jpeg 会降低图像质量(对于照片来说是可以的,但是对于屏幕截图,使用像素绘制的字体,它会带来一些不好的效果- 外观效果)
回答by Rufinus
A quality setting of 100% ist quite to large. try 85 or 90% you wont see a difference on most of the images.
100% 的质量设置相当大。尝试 85% 或 90% 您不会在大多数图像上看到差异。
see: http://www.ampsoft.net/webdesign-l/jpeg-compression.html
回答by Roshan Kr Soni
it moving compressed image with original. actually i want to move only compressed image that starts with "rxn-".
它使用原始移动压缩图像。实际上我只想移动以“rxn-”开头的压缩图像。
include("do.php");
session_start();
if(is_array($_FILES)) {
for($i=0; $i<count($_FILES['userImage']['tmp_name']); $i++){
if(is_uploaded_file($_FILES['userImage']['tmp_name'][$i])) {
$sourcePath = $_FILES['userImage']['tmp_name'][$i];
$upload_dir = "images/";
$targetPath = "images/".basename($_FILES['userImage']['name'][$i]);
$source_image = "images/".basename($_FILES['userImage']['name'][$i]);
$imageName =$_FILES['userImage']['name'][$i];
$imageFileType = strtolower(pathinfo($targetPath,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["userImage"]["tmp_name"][$i]);
if (file_exists($targetPath)) {
// echo "<span style='color:red;'> file already exists</span> ";
}
if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "<span style='color:red;'>File is not an image.</span><br>";
$uploadOk = 0;
}
if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg"
|| $imageFileType =="gif" ) {
if(move_uploaded_file($sourcePath,$targetPath))
//if(1)
{
$image_destination = $upload_dir."rxn-".$imageName;
$compress_images = compressImage($source_image, $image_destination);
$pId=$_SESSION['pId'];
$sql="insert into image(p_id,img_path) values('$pId','$compress_images')";
$result = mysql_query($sql);
echo "
<div class='col-sm-3' id='randomdiv' style='padding-bottom: 15px;'>
<div class='bg_prcs uk-height-small uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light uk-card-default uk-card-hover imgt' data-src='$image_destination' uk-img>
</div>
</div>
";
}
}
else{ echo "<span style='color:red;'> only JPG, JPEG, PNG & GIF files are allowed.</span>";
}
}
}
}
// created compressed JPEG file from source file
function compressImage($source_image, $compress_image) {
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/gif') {
$source_image = imagecreatefromgif($source_image);
imagegif($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 6);
}
return $compress_image;
}
?>

