Jump to content

resize on the fly script, can i adjust this to work on multiple files?


jesushax

Recommended Posts

Ok here is the finished part. Just look it over in case I forgot something.

<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/header.php');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/admin_head.php');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/admin_access.inc');

$absolute_path = $_SERVER['DOCUMENT_ROOT'] . "/news/uploads/";//Absolute path to where files are uploaded
$thumb_path = $_SERVER['DOCUMENT_ROOT'] . "/news/uploads/thumbs/";   //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 = "4000000";                                       //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 = "4";                                             //total number of extensions in array below
$extensions = array(".jpg", ".jpeg", ".png", ".gif");         //List extensions you want files uploaded to be

function resampleimage($maxsize, $sourcefile, $destination, $imgcomp=0){
// SET THE IMAGE COMPRESSION
$g_imgcomp=100-$imgcomp;
  // CHECK TO SEE IF THE IMAGE EXISTS FIRST
  if(file_exists($sourcefile)){
  // FIRST WE GET THE CURRENT IMAGE SIZE
  $g_is=getimagesize($sourcefile);
    /********* CALCULATE THE WIDTH AND THE HEIGHT ***************/
    // CHECK TO SEE IF THE WIDTH AND HEIGHT ARE ALREADY SMALLER THAN THE MAX SIZE
    if($g_is[0] <= $maxsize && $g_is[1] <= $maxsize){
    // LEAVE WIDTH AND HEIGHT ALONE IF IMAGE IS SMALLER THAN MAXSIZE
    $new_width=$g_is[0];
    $new_height=$g_is[1];
    } else {
    // GET VALUE TO CALCULATE WIDTH AND HEIGHT
    $w_adjust = ($maxsize / $g_is[0]);
    $h_adjust = ($maxsize / $g_is[1]);
      // CHECK TO WHICH DIMENSION REQUIRES THE SMALLER ADJUSTMENT
      if($w_adjust <= $h_adjust){
      // CALCULATE WIDTH AND HEIGHT IF THE WIDTH VALUE IS SMALLER
      $new_width=($g_is[0]*$w_adjust);
      $new_height=($g_is[1]*$w_adjust);
      } else {
      // CALCULATE WIDTH AND HEIGHT IF THE HEIGHT VALUE IS SMALLER
      $new_width=($g_is[0]*$h_adjust);
      $new_height=($g_is[1]*$h_adjust);
      }
    }
  //SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER THE LAST "." )
$image_type = strrchr($sourcefile, ".");

//SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
switch($image_type) {
	case '.jpg':
		$img_src = imagecreatefromjpeg($sourcefile);
		break;
	case '.jpeg':
		$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;
}
  // CREATE THE TRUE COLOR IMAGE WITH NE WIDTH AND HEIGHT
  $img_dst=imagecreatetruecolor($new_width,$new_height);
  // RESAMPLE THE IMAGE TO NEW WIDTH AND HEIGHT
  imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width, $new_height, $g_is[0], $g_is[1]);
  // OUTPUT THE IMAGE AS A JPEG.
  // THIS CAN BE CHANGED IF YOU WANT TRANSPARENCY OR PREFER ANOTHER FORMAT. MAKE SURE YOU CHANGE HEADER ABOVE.
  imagejpeg($img_dst, $destination, 100);
  // DESTROY THE NEW IMAGE
  imagedestroy($img_dst);
  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 .= "  $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>";

?>
<p><? echo $pichead; ?></p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" />
<p>Pictures:<br />
<?php
$files = 2;   // Change this line for the number of uploads you want to allow
for($i=1; $i<=$files; $i++){
echo "Picture $i <input type=\"file\" name=\"pictures[]\" /><br />\n";
}
?>
<h3>Add News</h3>
<table width="100%">
<tr>
  <td  style="width:80%;"><span style="width:20%;">News Title: </span></td>
</tr>
<tr>
<td style="width:80%;">
<input type="text" size="45" name="NewsTitle" /></td>
</tr>
<tr>
  <td> </td>
</tr>
<tr>
  <td>News Brief :</td>
</tr>
<tr>
  <td><textarea name="NewsShort" cols="70" rows="12" id="txtNewsShort"></textarea></td>
  </tr>
<tr>
  <td > </td>
</tr>
<tr>
   <td><strong>Attachments:</strong></td>
</tr>
<tr>
  <td>Attachment<input name="NewsAttachment[]" type="file" id="ufile[]" size="25" /> </td>
</tr>
<tr>
  <td> </td>
</tr>
<tr>
  <td >News Full :</td>
</tr>
<tr>
  <td ><textarea name="NewsFull" cols="70" rows="12" id="txtNewsFull"></textarea></td>
  </tr>
<tr>
  <td > </td>
</tr>
<tr>
<td  style="height:32px;"><div style=" text-align:center">
<input type="submit" name=submit value="Add News" />
<input type="button" name="Reset" value="Cancel" alt="Cancel" onclick="document.location='/admin/news/index.php'" />
</div></td>
</tr>
</table>
</form>
<?php
} else {
$i=0;
$insert_array = 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];
  $file_size = $_FILES["pictures"]['size'][$i];
  $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{
          $j = $i + 1;
          $ikey = "NewsImage$j";
          $insert_array[$ikey] = $file_name;
          // first move the file to
          move_uploaded_file($file, $absolute_path.$file_name);
          // Save full size image with max width/height
          resampleimage("800", $absolute_path.$file_name, $absolute_path.$file_name, 0);  // Comment this line out if you don't want to resize the image change the "800" to the size you want
          // Save thumb image with max width/height of 200
          resampleimage("125", $absolute_path.$file_name, $thumb_path.$file_name, 0); // Comment this line out if you don't want to create a thumbnail, change the 200 to the size you want
          }
        }
      }
    }
  $i++;
  echo $endresult."<br>";
  }

//$ext = strrchr($_FILES["pictures"]['name'][$i], ".");
//$n = $i+1;
//$file_name = "file".$n.$ext;

$path1= $_SERVER['DOCUMENT_ROOT'] . "/news/uploads/".$_FILES['NewsAttahcment']['name'][0];
move_uploaded_file($_FILES['NewsAttachment']['tmp_name'][0], $path1);
$insert_array['NewsAttachment'] = $_FILES['NewsAttachment']['name'][0];

// Prepare date for mysql insert
  foreach($_POST as $key => $val){
    if($key != "submit"){
    $insert_array[$key] = $val;
    }
  }
  $insert_array['NewsDateAdded'] = date("d/m/y");
  $insert_array['NewArchive'] = "0";
  $fields = "";
  $values = "";
  foreach($insert_array as $field => $value){
  $fields .= "$field`, `";
  $values .= "$value', '";
  }
  $fields = substr($fields, 0, -4);  // remove the last ticks
  $values = substr($values, 0, -4);  //remove the last quotes
  $sql = "INSERT INTO tblNews (`$fields`) VALUES ('$values')";
  mysql_query($sql) or die(mysql_error());
  header("Location: /admin/news/index.php");

}
echo "</div>";
include($_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php');
?>

 

I renamed the form input fields to match your field names in the table so we can prepare the data in a loop instead of doing in manually.

 

please ask if you don't understand something.

 

Ray

Link to comment
Share on other sites

thanks all sorted now

 

also tried uploading a 2mb image

 

got thsi error again

 

Fatal error: Allowed memory size of 20971520 bytes exhausted (tried to allocate 8000 bytes) in /home/fhlinux153/c/cwservicesltd.co.uk/user/htdocs/admin/news/add_news.php on line 57

 

but the file is uploaded its jus teh thumbnail that isnt created

and my upload limit is 4mb

 

what could this mean?

 

cheers

Link to comment
Share on other sites

problem may be that you are uploading only a 2MB file but the script is taking up more than that because when it generates the images, that takes up more memory also. There is a setting in php.ini file to change the amount of memory a script uses. raise that up and it might help. Look at these settings

 

;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 900     ; Maximum execution time of each script, in seconds
max_input_time = 900	; Maximum amount of time each script may spend parsing request data
memory_limit = 64M      ; Maximum amount of memory a script may consume (8MB)


upload_max_filesize = 10M

 

These are what mine are at but my box is an internal server.

 

Ray

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.