[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to reduce file size on upload in php ?

Posted on 2009-04-24
3
Medium Priority
?
1,428 Views
Last Modified: 2013-12-12
i want to reduce the file size of an image while its uploading on server.how it is possible with php ?
0
Comment
Question by:developer2966
1 Comment
 
LVL 14

Accepted Solution

by:
shobinsun earned 2000 total points
ID: 24222573
HI,

you can use   imagecopyresampled() function.

For example:

Look at this:


<?php
$absolute_path = "/path/to/image/folder"; //Absolute path to where files are uploaded
$thumb_path = "/path/to/thumbnail/folder";  //Absolute path to where thumbs are to be stored if you want this
$size_limit = "yes"; //do you want a size limit yes or no.
$limit_size = "600000"; //How big do you want size limit to be in bytes
$limit_ext = "yes"; //do you want to limit the extensions of files uploaded
$ext_count = "3"; //total number of extensions in array below
$extensions = array(".jpg", ".png", ".gif"); //List extensions you want files uploaded to be
 
function resampimage($maxwidth, $maxheight, $sourcefile, $imgcomp=0)
   {
   $g_imgcomp=100-$imgcomp;
   if(file_exists($sourcefile))
       {
       $g_is=getimagesize($sourcefile);
       $w_adjust = ($maxwidth / $g_is[0]);
       $h_adjust = ($maxheight / $g_is[1]);
       if($w_adjust <= $h_adjust)
           {
           $new_width=($g_is[0]*$w_adjust);
           $new_height=($g_is[1]*$w_adjust);
           }
           else
           {
           $new_width=($g_is[0]*$h_adjust);
           $new_height=($g_is[1]*$h_adjust);
           }
          //SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER . )
       $image_type = strrchr($sourcefile, ".");
 
       //SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
      switch($image_type) {
         case '.jpg':
            $img_src = imagecreatefromjpeg($sourcefile);
            break;
         case '.png':
            $img_src = imagecreatefrompng($sourcefile);
            break;
         case '.gif':
            $img_src = imagecreatefromgif($sourcefile);
            break;
         default:
            echo("Error Invalid Image Type");
            die;
            break;
         }
       $img_dst=imagecreatetruecolor($new_width,$new_height);
       imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width, $new_height, $g_is[0], $g_is[1]);
       imagejpeg($img_dst);
       imagedestroy($img_dst);
       imagedestroy($img_src);
       return true;
       }
       else
       return false;
   }
 
if(!isset($_POST['submit'])){
$extens = '';
 
        if (($extensions == "") or ($extensions == " ") or ($ext_count == "0") or ($ext_count == "") or ($limit_ext != "yes") or ($limit_ext == "")) {
           $extens = "any extension";
        } else {
        $ext_count2 = $ext_count+1;
        for($counter=0; $counter<$ext_count; $counter++) {
            $extens .= "&nbsp; $extensions[$counter]";
        }
        }
        if (($limit_size == "") or ($size_limit != "yes")) {
            $limit_size = "any size";
        } else {
            $limit_size .= " bytes";
            $mb_size = ($limit_size/1000000);
        }
        $pichead = "<li><font size=\"2\" color=660000>File extension must be $extens<b>";
        $pichead .="</b></font>
        <li><font size=\"2\" color=660000>Maximum file size is $limit_size ($mb_size MB)</font></li>
        <li><font size=\"2\" color=660000>No spaces in the filename</font></li>";
?>
<html>
<head>
<title>HTML Form for uploading image to server</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<html>
<title>Add Vehicle Form</title>
<body>
<p><? echo $pichead; ?></p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<p>Pictures:<br />
1 <input type="file" name="pictures[]" /><br />
2 <input type="file" name="pictures[]" /><br />
3 <input type="file" name="pictures[]" /><br />
4 <input type="file" name="pictures[]" /><br />
5 <input type="file" name="pictures[]" /><br />
6 <input type="file" name="pictures[]" /><br />
<input type="submit" name=submit value="Send" />
</p>
</form>
<?php
} else {
$i=0;
$photoarray = array();
  foreach ($_FILES["pictures"]["error"] as $key => $error) {
  $file_name =  $_FILES["pictures"]['name'][$i]; // can call this anything you like this will take the original name
  $file =  $_FILES["pictures"]['tmp_name'][$i];
  $photoarray[$i+1]= $file_name;
  $endresult = "<font size=\"4\" color=990000>$file_name uploaded successfully</font>";
    if ($file_name == "") {
    $pic = $i+1;
    $endresult = "<font size=\"4\" color=990000>Pic#$pic Not selected</font>";
    }else{
      if(file_exists("$absolute_path/$file_name")) {
      $endresult = "<font size=\"4\" color=990000>File Already Existed</font>";
      } else {
        if (($size_limit == "yes") && ($limit_size < $file_size)) {
        $endresult = "<font size=\"4\" color=990000>File was to big</font>";
        } else {
        $ext = strrchr($file_name,'.');
          if (($limit_ext == "yes") && (!in_array($ext,$extensions))) {
          $endresult = "<font size=\"4\" color=990000>File is wrong type</font>";
          }else{
          // Save full size image with max width/height
          resampimage(1000,1000,$file,"$absolute_path/$file_name",0);
          // Save thumb image with max width/height of 200
          // resampimage(200,200,$file,"$thumb_path/$file_name",0);
          }
        }
      }
    }
  $i++;
  echo $endresult."<br>";
  }
}
?>
</body>
</html>

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month17 days, 22 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question