上传时压缩图像文件大小?

14
我正在将产品屏幕截图上传到我的网站... 我想上传原始图像,并为其创建缩略图,但在上传两个文件后,所创建的缩略图文件大小比预期稍大。 有没有办法在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."'>"; 

      }
    } ?>

请指引我正确的方向...谢谢

7个回答

17

不要将100作为imagejpeg()的质量参数 - 通常超过90就足够了,否则只会得到更大的JPEG图像。对于缩略图,请尝试使用75,并逐渐降低质量/大小之间的平衡,直到满意为止。

//try this
imagejpeg($tn, $save, 75) ; 

3
这段代码是用来查找图片服务器位置的。但我想要从本地图片调整大小并上传。 - logan

6

你好 @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;

      }
    } 
?>

2

默认的质量设置是75,但如果您使用它,您会发现质量会明显降低。90可以为您提供出色的图像质量,并将文件大小减少一半。如果您想进一步减小文件大小,请使用85或80,但不要低于这个值。


2

应该是60,代表60%。

例如: 如果你在Photoshop中打开一个图像,尝试将其保存为Web并选择jpg格式,您会发现使用60仍然保持高质量,但文件大小更小。如果您希望更低的质量,即颜色失真更多的话,则可以选用更低的数字。

超过60不会给您更好的效果,只会增加文件大小。

这是网络图片优化的标准。保持高品质,同时尽可能降低文件大小。


1

1

如果使用jpeg,使用75到85之间的质量通常是可以接受的(而100占用了太多空间,对于并不那么重要的收益来说),至少对于照片来说。

顺便说一下,如果您正在处理截图,使用PNG可能会获得更好的质量: jpeg会使图像变劣 (这对于照片来说还可以接受,但对于使用像素绘制字体的截图来说,可能会产生一些不好看的效果)


0

it moving compressed image with original. actually i want to move only compressed image that starts with "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;
                }


                ?>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接