Jump to content

Recommended Posts

I am VERY new to PHP, but I am trying to adapt code from http://www.4wordsystems.com/php_image_resize.php to work with multiple images.  Can any please help?

 

I know I need to place it in a loop of some kind, but I don't know how to write the code for that.  Here is the code:

 

HTML FORM CODE:

<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile"/>
<input type="submit"/>
</form>

 

upload.php CODE:

<?php

// This is the temporary file created by PHP
$uploadedfile = $_FILES['uploadfile']['tmp_name'];

// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);

// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);

// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

// For our purposes, I have resized the image to be
// 150 pixels high, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max height other than
// 150, simply change the $newheight variable
$newheight=150;
$newwidth=($width/$height)*150;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/thumb_". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.

echo "Successfully Uploaded: <img src='".$filename."'>";

?> 

Link to comment
https://forums.phpfreaks.com/topic/139049-multiple-image-upload-and-resize-form/
Share on other sites

First of all you can upload only ONE file per input field, so the very first thing you should do is to create more input fields in your HTML code. I recommend you to name them with numeric values, as it would be easier to access them via PHP, like:

 

img1, img2, img3, etc.

 

So the HTML would be like this

<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="img1"/>
<input type="file" name="img2"/>
<input type="file" name="img3"/>
<input type="submit"/>
</form>

 

then in the PHP code, create a function that resize the image. I will create a while loop, to access each of the images:

<?php

function imgReisize($uploadedfile, $Destination, $Thumb){
//this is the function that will resize and copy our images

// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);

// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);

// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = $Destination;
imagejpeg($tmp,$filename,100);

// For our purposes, I have resized the image to be
// 150 pixels high, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max height other than
// 150, simply change the $newheight variable
$newheight=150;
$newwidth=($width/$height)*150;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = $Thumb;
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.

echo "Successfully Uploaded: <img src='".$filename."'>";
}

    if(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="./imgs/";  //Place the destination dir here
     $ThumbDir="./imgs/thumbs/";  //Place the thumb dir here

       while($_FILES["img".$imgNumb][tmp_name]){
              $Unique=microtime(); // We want unique names, right?
              $destination=$DestinationDir.md5($Unique).".jpg";
              $thumb=$ThumbDir.md5($Unique).".jpg";
              imgReisize($_FILES["img".$imgNumb][tmp_name], $destination, $thumb);
              $imgNumb++;
       }
    }
?> 

OK, so I tried running the codes from above, and it runs with no errors, however, no images or thumbs are actually saved to my server, and when it finishes running it just ends on a blank page with no echo of whether or not the upload was successful.

 

Do I need to move the if and while loops that you wrote at the end of the code to somewhere within the code?

Well, I created the code only as an example, however, do you have imgs and imgs/thumbs directories. If they don't exist, PHP wouldn't create them, so you need to create them manually. Try again and tell us if you have more problems

I double checked to make sure the folder names called for in the script exist on my server and they do, so I don't know!

 

I was able to get that code to work in it's basic form (resizing and saving one image with a thumbnail), so I know it works to write on the server with permissions and whatnot - I don't know why it isn't working now!

I recommend you to change your HTML code because I really don't like name-unspecified variables

<form action="" method="post" enctype="multipart/form-data" >
<input type="file" name="img1"/>
<input type="file" name="img2"/>
<input type="file" name="img3"/>
<input type="submit" name="submit" value="Submit"/>
</form>

 

I'm using modified version of a function I found at http://php.net. But I can't remember where is it. So, you could use thins function which I found at http://bg2.php.net/manual/en/function.imagecreatefromjpeg.php (Posted by Ninjabear)

<?php
function resize($img, $thumb_width, $newfilename) 
{ 
  $max_width=$thumb_width;

    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2')) 
    {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }

    //Get Image size info
    list($width_orig, $height_orig, $image_type) = getimagesize($img);
    
    switch ($image_type) 
    {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }
    
    /*** calculate the aspect ratio ***/
    $aspect_ratio = (float) $height_orig / $width_orig;

    /*** calculate the thumbnail width based on the height ***/
    $thumb_height = round($thumb_width * $aspect_ratio);
    

    while($thumb_height>$max_width)
    {
        $thumb_width-=10;
        $thumb_height = round($thumb_width * $aspect_ratio);
    }
    
    $newImg = imagecreatetruecolor($thumb_width, $thumb_height);
    
    /* Check if this image is PNG or GIF, then set if Transparent*/  
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
    
    //Generate the file, and rename it to $newfilename
    switch ($image_type) 
    {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}
//This stuff is outside of the function. It operates with our images
    if(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="images/";  //Place the destination dir here
     $ThumbDir="images/thumb_";  //Place the thumb dir here

       do{
              $Unique=microtime(); // We want unique names, right?
              $destination=$DestinationDir.md5($Unique).".jpg";
              $thumb=$ThumbDir.md5($Unique).".jpg";

               $IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
              echo resize($_FILES["img$imgNumb"][tmp_name], $IMG[0], $destination);
              $imgNumb++;
         } while($_FILES["img$imgNumb"][name]);
    }
?>

 

Hope this finally works :D

Editing my last post, I ran the code adding in the variable of

 

$thumb_width=150;

 

This works in that it now resizes all of the images to a width of 150 - that's a big step forward!  However, it only saves the images ONCE, and does not actually save a larger version of the file - what would I need to do to make sure it uploads BOTH the thumbs AND the full?

So what I have done to get both my full image and my thumb is repeat the resizing function, and everything works great!

 

What I want to do now is ELIMINATE the unique name that each photo is given and maintain the name that they have from the harddrive on my computer.

 

Here is the code used in this script in the naming process:

    if(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="images/thumb_";  //Place the destination dir here
     $ThumbDir="images/thumb_";  //Place the thumb dir here

       do{
              $Unique=microtime(); // We want unique names, right?
              $destination=$DestinationDir.md5($Unique).".jpg";
              $thumb=$ThumbDir.md5($Unique).".jpg";

               $IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
              echo resize2($_FILES["img$imgNumb"][tmp_name], $IMG[0], $destination);
              $imgNumb++;
         } while($_FILES["img$imgNumb"][name]);
    }

 

And here is what I have tried, changing the value of "$Unique", to:

if(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="images/";  //Place the destination dir here
     $LargeDir="images/";  //Place the large image dir here

       do{
              $Unique=$_FILES['img$imgNumb']['name']; // We want unique names, right?
              $destination=$DestinationDir.($Unique).".jpg";
              $thumb=$ThumbDir.($Unique).".jpg";

               $IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
              echo resize($_FILES["img$imgNumb"][tmp_name], $IMG[0], $destination);
              $imgNumb++;
         } while($_FILES["img$imgNumb"][name]);
    }

 

Needless to say my code doesn't rename the files properly - they still save to the server, but with ".jpg" - no file name.  With the original code they had a randomized name, but I want to maintain the original name.

 

What can I change the code to to obtain this?

You have left the braces from the md5 function. Remove them

<?phpif(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="images/";  //Place the destination dir here
     $LargeDir="images/";  //Place the large image dir here

       do{
              $Unique=$_FILES['img$imgNumb']['name']; // We want unique names, right?
              $destination=$DestinationDir.$Unique.".jpg";
              $thumb=$ThumbDir.$Unique.".jpg";

               $IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
              echo resize($_FILES["img$imgNumb"][tmp_name], $IMG[0], $destination);
              echo resize($_FILES["img$imgNumb"][tmp_name], 120, $thumb); //That was what I forgot last time
              $imgNumb++;
         } while($_FILES["img$imgNumb"][name]);
    }
?>

 

  • 11 months later...

Hello all,

 

I tryed the options, but the script is not working in the file below. Can anyone give me the solution for implementing the $imgNumb++;

Note: i use joomla.

 

<?php

define( "_VALID_MOS", 1 );

/** security check */
require( "authEA.php" );

include_once ( $mosConfig_absolute_path . '/administrator/components/com_botenaanbod/class.botenaanbod.php' );
include_once ( $mosConfig_absolute_path . '/administrator/components/com_botenaanbod/configuration.php' );

if (file_exists($mosConfig_absolute_path.'/components/com_botenaanbod/languages/'.$mosConfig_lang.'.php')) {
include_once($mosConfig_absolute_path.'/components/com_botenaanbod/languages/'.$mosConfig_lang.'.php');
} else {
   	include_once($mosConfig_absolute_path.'/components/com_botenaanbod/languages/english.php');
}

// File Upload
if (isset($_FILES['userfile'])) {

$cfg 		= $_POST;
$css		= $cfg['css'];
$objid 		= $cfg['objid'];

// is this the first image of this object?
$sql = "SELECT count(id) FROM #__botenaanbod_images WHERE objid = $objid";
$database->setQuery($sql);
$result	= $database->loadResult();

$pn 		= ( $result == 0 )? 1 : ($result+1);							
$src_file	= (isset($_FILES['userfile']['tmp_name']) ? $_FILES['userfile']['tmp_name'] : "");

// check individual settings	
$cfg['picpath']			= (trim($cfg['picpath']) != trim($ea_picpath))? $cfg['picpath'] : $ea_picpath;
$cfg['maxpicsize'] 		= ($cfg['maxpicsize'] != $ea_maxpicsize)? $cfg['maxpicsize'] : $ea_maxpicsize;
   
$cfg['imgwidth']		= ($cfg['imgwidth'] != $ea_imgwidth)? $cfg['imgwidth'] : $ea_imgwidth;
$cfg['imgheight']		= ($cfg['imgheight'] != $ea_imgheight)? $cfg['imgheight'] : $ea_imgheight;
$cfg['imageprtn']		= (isset($cfg['imgprtn']))? 1 : 0;
$cfg['imgqulty']		= ($cfg['imgqulty'] != $ea_imgqulty)? $cfg['imgqulty'] : $ea_imgqulty;
    
$cfg['createTb']		= (isset($cfg['createthumb']))? 1:0;
$cfg['tbwidth']			= ($cfg['tbwidth'] != $ea_tbwidth)? $cfg['tbwidth'] : $ea_tbwidth;
$cfg['tbheight']		= ($cfg['tbheight'] != $ea_tbheight)? $cfg['tbheight'] : $ea_tbheight;
$cfg['thumbprtn']		= (isset($cfg['tbprtn']))? 1 : 0;
$cfg['tbqulty']			= ($cfg['tbqulty'] != $ea_tbqulty)? $cfg['tbqulty'] : $ea_tbqulty;		

$dest_dir 				= $mosConfig_absolute_path.$cfg['picpath'];
$type		 			= explode('.',strtolower($_FILES['userfile']['name'])); 
$file['type']			= '.'.$type[1];	

$file['name'] 			= "ea".time();
$dest_file 				= $dest_dir.$file['name'].$file['type'];

$file['tbname'] 		= "tea".time();
$dest_thmb 			= $dest_dir.$file['tbname'].$file['type'];

if (eregi("[^0-9a-zA-Z_ ]", $cfg['title'])) {
		echo "<script> alert('"._EAB_GL_TITLEERROR."'); window.history.go(-1);</script>\n";
		exit();
}
if(filesize($src_file) > (intval($cfg['maxpicsize']) * 1000)) {
		echo "<script> alert('"._EAB_GL_UTB."'); window.history.go(-1);</script>\n";
		exit();	
}
if (file_exists($dest_file)) {
		echo "<script> alert('"._EAB_GL_FAE."'); window.history.go(-1);</script>\n";
		exit();
}
if (
	(strcasecmp($file['type'],".gif")) 
	&& (strcasecmp($file['type'],".jpg"))
	&& (strcasecmp($file['type'],".png"))
	) {
		echo "<script>alert('The file can be gif, jpg, png'); window.history.go(-1);</script>\n";
		exit();     // AVI, MPEG hinzufügen  -> Active-X control für MSIE -> classid="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A"
}
$error = "";
if($file['type'] == ".gif" || $file['type'] == ".jpg" || $file['type'] == ".png" ) {

	# create images & thumbs
	$error = resizeIMG(0,$src_file,$dest_file,$cfg['imgwidth'],$cfg['imgheight'],$cfg['imageprtn'],$cfg['imgqulty']);

	if($cfg['createTb'] == 1) {
    		$error .= resizeIMG(1,$src_file,$dest_thmb,$cfg['tbwidth'],$cfg['tbheight'],$cfg['thumbprtn'],$cfg['tbqulty']);
    	}
    
}
else{
	if(@copy($src_file,$dest_file)) $error = "";
	else $error = _EAB_GL_UFS;
}
  
    if($error == "") {       					  						
    	$pic = new EAImage($database);       					       					
       					       					       					
    	if (!$pic->bind( $_POST )) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}       					
       					       					
    	$pic->title			= trim($cfg['title']);
	$pic->description	= trim($cfg['description']);
	$pic->fname			= $file['name'];
	$pic->type			= $file['type'];
	$pic->path			= trim($cfg['picpath']);
	$pic->owner			= $my->id;
	$pic->ordering		= 0;
	$pic->publish		= 1;

	if (!$pic->check()) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}
    	if (!$pic->store()) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}
    	$pic->checkin();
       				
       	$pic->updateOrder( "objid=$objid AND type='$pic->type'" );       				
       	$msg = sprintf (_EA_GL_UPLOADSUCCESS, $pn);     				
       	//$msg = _EA_GL_UPLOADSUCCESS;

	mosRedirect("admin.gallery.html.php?action=manage&css=".$css."&objid=".$pic->objid."&msg=".$msg."&uid=".$my->id."&pn=".$pn);
}
    else{
    	echo "<script> alert('"._EAB_GL_UFS."'); window.history.go(-1); </script>\n";
    }			
}
else{
	echo "<script> alert('"._EAB_GL_NOFILE."'); window.history.go(-1); </script>\n";	
	}	


# Thanks to Arthur Konze for this function ##################################################
function resizeIMG($is_thmb,$src_file,$dest_file,$width,$height,$prop,$quality){
	global $ea_gplib, $ea_watermark, $mosConfig_live_site;

	$imagetype = array( 1 => 'GIF', 2 => 'JPG', 3 => 'PNG' );
  		$imginfo = getimagesize($src_file);
	if ($imginfo == null) {
  			$error = _EAB_GL_NOFILE;
         	return $error;
        }

  		$imginfo[2] = $imagetype[$imginfo[2]];

  		// GD can only handle JPG & PNG images
  		if ($imginfo[2] != 'JPG' && $imginfo[2] != 'PNG' && ($ea_gplib == 'gd1' || $ea_gplib == 'gd2')) {
  			$error = "ERROR: GD can only handle JPG and PNG files!";
         	return $error;
        }

  		// source height/width
  		$srcWidth = $imginfo[0];
  		$srcHeight = $imginfo[1];

	if($prop == 1) {
  			$ratio = $srcHeight / $height;
  			#$ratio = max($srcWidth, $srcHeight) / $new_size;
  			$ratio = max($ratio, 1.0);
  		$destWidth = (int)($srcWidth / $ratio);
  			$destHeight = (int)($srcHeight / $ratio);
	}
	else{
		$ratio = $srcHeight / $height;
  			#$ratio = max($srcWidth, $srcHeight) / $new_size;
  			$ratio = max($ratio, 1.0);
  		$destWidth = (int)($srcWidth / $ratio);
  			$destHeight = (int)($srcHeight / $ratio);
	}

  		// Method for thumbnails creation
  		switch ($ea_gplib) {

  		case "gd1" :
    		
    		if (!function_exists('imagecreatefromjpeg')) {
        		$error = _EAB_GL_NOGD;
        		return $error;
    		}
    		if ($imginfo[2] == 'JPG') $src_img = imagecreatefromjpeg($src_file);
    		else $src_img = imagecreatefrompng($src_file);
    		
    		if (!$src_img){
      			$error = $lang_errors['invalid_image'];
      			return $error;
    		}

    		$dst_img = imagecreate($destWidth, $destHeight);
		imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
		if(!$is_thmb && $ea_watermark){
			$wmstr = substr($mosConfig_live_site,7);
			$wmstr = "(c)" . $wmstr;
			$ftcolor = imagecolorallocate($dst_img,239,239,239);
			imagestring ($dst_img, 9,10, $destHeight-20, $wmstr, $ftcolor);
    		}
		imagejpeg($dst_img, $dest_file, $quality);
    		imagedestroy($src_img);
    		imagedestroy($dst_img);
    	
    	break;

  		case "gd2" :
    	
    		if (!function_exists('imagecreatefromjpeg')) {
        		$error = _EAB_GL_NOGD2;
        		return $error;
    		}
    		if (!function_exists('imagecreatetruecolor')) {
        		$error = "GD2 image library does not support truecolor thumbnailing!";
        		return $error;
    		}
    		if ($imginfo[2] == 'JPG') $src_img = imagecreatefromjpeg($src_file);
    		else $src_img = imagecreatefrompng($src_file);
    		
    		if (!$src_img){
      			$error = $lang_errors['invalid_image'];
      			return $error;
    		}

    		$dst_img = imagecreatetruecolor($destWidth, $destHeight);			
    		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
    		if(!$is_thmb && $ea_watermark){
			$wmstr = substr($mosConfig_live_site,7);
			$wmstr = "(c)" . $wmstr;
			$ftcolor = imagecolorallocate($dst_img,239,239,239);
			imagestring ($dst_img, 9,10, $destHeight-20, $wmstr, $ftcolor);
    		}
		imagejpeg($dst_img, $dest_file, $quality);
    		imagedestroy($src_img);
    		imagedestroy($dst_img);
    		break;
  		}

  		// Set mode of uploaded picture
  		chmod($dest_file, octdec('644'));

  		// We check that the image is valid
  		$imginfo = getimagesize($dest_file);
  		if ($imginfo == null){
  			$error = _EAB_GL_NOTHMBCREAT;
    		return $error;
  		}
  		else return;

  	}		
?>

Hello all,

 

I tryed the options, but the script is not working in the file below. Can anyone give me the solution for implementing the $imgNumb++;

Note: i use joomla.

 

<?php

define( "_VALID_MOS", 1 );

/** security check */
require( "authEA.php" );

include_once ( $mosConfig_absolute_path . '/administrator/components/com_botenaanbod/class.botenaanbod.php' );
include_once ( $mosConfig_absolute_path . '/administrator/components/com_botenaanbod/configuration.php' );

if (file_exists($mosConfig_absolute_path.'/components/com_botenaanbod/languages/'.$mosConfig_lang.'.php')) {
include_once($mosConfig_absolute_path.'/components/com_botenaanbod/languages/'.$mosConfig_lang.'.php');
} else {
   	include_once($mosConfig_absolute_path.'/components/com_botenaanbod/languages/english.php');
}

// File Upload
if (isset($_FILES['userfile'])) {

$cfg 		= $_POST;
$css		= $cfg['css'];
$objid 		= $cfg['objid'];

// is this the first image of this object?
$sql = "SELECT count(id) FROM #__botenaanbod_images WHERE objid = $objid";
$database->setQuery($sql);
$result	= $database->loadResult();

$pn 		= ( $result == 0 )? 1 : ($result+1);							
$src_file	= (isset($_FILES['userfile']['tmp_name']) ? $_FILES['userfile']['tmp_name'] : "");

// check individual settings	
$cfg['picpath']			= (trim($cfg['picpath']) != trim($ea_picpath))? $cfg['picpath'] : $ea_picpath;
$cfg['maxpicsize'] 		= ($cfg['maxpicsize'] != $ea_maxpicsize)? $cfg['maxpicsize'] : $ea_maxpicsize;
   
$cfg['imgwidth']		= ($cfg['imgwidth'] != $ea_imgwidth)? $cfg['imgwidth'] : $ea_imgwidth;
$cfg['imgheight']		= ($cfg['imgheight'] != $ea_imgheight)? $cfg['imgheight'] : $ea_imgheight;
$cfg['imageprtn']		= (isset($cfg['imgprtn']))? 1 : 0;
$cfg['imgqulty']		= ($cfg['imgqulty'] != $ea_imgqulty)? $cfg['imgqulty'] : $ea_imgqulty;
    
$cfg['createTb']		= (isset($cfg['createthumb']))? 1:0;
$cfg['tbwidth']			= ($cfg['tbwidth'] != $ea_tbwidth)? $cfg['tbwidth'] : $ea_tbwidth;
$cfg['tbheight']		= ($cfg['tbheight'] != $ea_tbheight)? $cfg['tbheight'] : $ea_tbheight;
$cfg['thumbprtn']		= (isset($cfg['tbprtn']))? 1 : 0;
$cfg['tbqulty']			= ($cfg['tbqulty'] != $ea_tbqulty)? $cfg['tbqulty'] : $ea_tbqulty;		

$dest_dir 				= $mosConfig_absolute_path.$cfg['picpath'];
$type		 			= explode('.',strtolower($_FILES['userfile']['name'])); 
$file['type']			= '.'.$type[1];	

$file['name'] 			= "ea".time();
$dest_file 				= $dest_dir.$file['name'].$file['type'];

$file['tbname'] 		= "tea".time();
$dest_thmb 			= $dest_dir.$file['tbname'].$file['type'];

if (eregi("[^0-9a-zA-Z_ ]", $cfg['title'])) {
		echo "<script> alert('"._EAB_GL_TITLEERROR."'); window.history.go(-1);</script>\n";
		exit();
}
if(filesize($src_file) > (intval($cfg['maxpicsize']) * 1000)) {
		echo "<script> alert('"._EAB_GL_UTB."'); window.history.go(-1);</script>\n";
		exit();	
}
if (file_exists($dest_file)) {
		echo "<script> alert('"._EAB_GL_FAE."'); window.history.go(-1);</script>\n";
		exit();
}
if (
	(strcasecmp($file['type'],".gif")) 
	&& (strcasecmp($file['type'],".jpg"))
	&& (strcasecmp($file['type'],".png"))
	) {
		echo "<script>alert('The file can be gif, jpg, png'); window.history.go(-1);</script>\n";
		exit();     // AVI, MPEG hinzufügen  -> Active-X control für MSIE -> classid="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A"
}
$error = "";
if($file['type'] == ".gif" || $file['type'] == ".jpg" || $file['type'] == ".png" ) {

	# create images & thumbs
	$error = resizeIMG(0,$src_file,$dest_file,$cfg['imgwidth'],$cfg['imgheight'],$cfg['imageprtn'],$cfg['imgqulty']);

	if($cfg['createTb'] == 1) {
    		$error .= resizeIMG(1,$src_file,$dest_thmb,$cfg['tbwidth'],$cfg['tbheight'],$cfg['thumbprtn'],$cfg['tbqulty']);
    	}
    
}
else{
	if(@copy($src_file,$dest_file)) $error = "";
	else $error = _EAB_GL_UFS;
}
  
    if($error == "") {       					  						
    	$pic = new EAImage($database);       					       					
       					       					       					
    	if (!$pic->bind( $_POST )) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}       					
       					       					
    	$pic->title			= trim($cfg['title']);
	$pic->description	= trim($cfg['description']);
	$pic->fname			= $file['name'];
	$pic->type			= $file['type'];
	$pic->path			= trim($cfg['picpath']);
	$pic->owner			= $my->id;
	$pic->ordering		= 0;
	$pic->publish		= 1;

	if (!$pic->check()) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}
    	if (!$pic->store()) {
    		echo "<script> alert('".$pic->getError()."'); window.history.go(-1); </script>\n";
    		exit();
    	}
    	$pic->checkin();
       				
       	$pic->updateOrder( "objid=$objid AND type='$pic->type'" );       				
       	$msg = sprintf (_EA_GL_UPLOADSUCCESS, $pn);     				
       	//$msg = _EA_GL_UPLOADSUCCESS;

	mosRedirect("admin.gallery.html.php?action=manage&css=".$css."&objid=".$pic->objid."&msg=".$msg."&uid=".$my->id."&pn=".$pn);
}
    else{
    	echo "<script> alert('"._EAB_GL_UFS."'); window.history.go(-1); </script>\n";
    }			
}
else{
	echo "<script> alert('"._EAB_GL_NOFILE."'); window.history.go(-1); </script>\n";	
	}	


# Thanks to Arthur Konze for this function ##################################################
function resizeIMG($is_thmb,$src_file,$dest_file,$width,$height,$prop,$quality){
	global $ea_gplib, $ea_watermark, $mosConfig_live_site;

	$imagetype = array( 1 => 'GIF', 2 => 'JPG', 3 => 'PNG' );
  		$imginfo = getimagesize($src_file);
	if ($imginfo == null) {
  			$error = _EAB_GL_NOFILE;
         	return $error;
        }

  		$imginfo[2] = $imagetype[$imginfo[2]];

  		// GD can only handle JPG & PNG images
  		if ($imginfo[2] != 'JPG' && $imginfo[2] != 'PNG' && ($ea_gplib == 'gd1' || $ea_gplib == 'gd2')) {
  			$error = "ERROR: GD can only handle JPG and PNG files!";
         	return $error;
        }

  		// source height/width
  		$srcWidth = $imginfo[0];
  		$srcHeight = $imginfo[1];

	if($prop == 1) {
  			$ratio = $srcHeight / $height;
  			#$ratio = max($srcWidth, $srcHeight) / $new_size;
  			$ratio = max($ratio, 1.0);
  		$destWidth = (int)($srcWidth / $ratio);
  			$destHeight = (int)($srcHeight / $ratio);
	}
	else{
		$ratio = $srcHeight / $height;
  			#$ratio = max($srcWidth, $srcHeight) / $new_size;
  			$ratio = max($ratio, 1.0);
  		$destWidth = (int)($srcWidth / $ratio);
  			$destHeight = (int)($srcHeight / $ratio);
	}

  		// Method for thumbnails creation
  		switch ($ea_gplib) {

  		case "gd1" :
    		
    		if (!function_exists('imagecreatefromjpeg')) {
        		$error = _EAB_GL_NOGD;
        		return $error;
    		}
    		if ($imginfo[2] == 'JPG') $src_img = imagecreatefromjpeg($src_file);
    		else $src_img = imagecreatefrompng($src_file);
    		
    		if (!$src_img){
      			$error = $lang_errors['invalid_image'];
      			return $error;
    		}

    		$dst_img = imagecreate($destWidth, $destHeight);
		imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
		if(!$is_thmb && $ea_watermark){
			$wmstr = substr($mosConfig_live_site,7);
			$wmstr = "(c)" . $wmstr;
			$ftcolor = imagecolorallocate($dst_img,239,239,239);
			imagestring ($dst_img, 9,10, $destHeight-20, $wmstr, $ftcolor);
    		}
		imagejpeg($dst_img, $dest_file, $quality);
    		imagedestroy($src_img);
    		imagedestroy($dst_img);
    	
    	break;

  		case "gd2" :
    	
    		if (!function_exists('imagecreatefromjpeg')) {
        		$error = _EAB_GL_NOGD2;
        		return $error;
    		}
    		if (!function_exists('imagecreatetruecolor')) {
        		$error = "GD2 image library does not support truecolor thumbnailing!";
        		return $error;
    		}
    		if ($imginfo[2] == 'JPG') $src_img = imagecreatefromjpeg($src_file);
    		else $src_img = imagecreatefrompng($src_file);
    		
    		if (!$src_img){
      			$error = $lang_errors['invalid_image'];
      			return $error;
    		}

    		$dst_img = imagecreatetruecolor($destWidth, $destHeight);			
    		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
    		if(!$is_thmb && $ea_watermark){
			$wmstr = substr($mosConfig_live_site,7);
			$wmstr = "(c)" . $wmstr;
			$ftcolor = imagecolorallocate($dst_img,239,239,239);
			imagestring ($dst_img, 9,10, $destHeight-20, $wmstr, $ftcolor);
    		}
		imagejpeg($dst_img, $dest_file, $quality);
    		imagedestroy($src_img);
    		imagedestroy($dst_img);
    		break;
  		}

  		// Set mode of uploaded picture
  		chmod($dest_file, octdec('644'));

  		// We check that the image is valid
  		$imginfo = getimagesize($dest_file);
  		if ($imginfo == null){
  			$error = _EAB_GL_NOTHMBCREAT;
    		return $error;
  		}
  		else return;

  	}		
?>

 

create your own thread to get assistance.

  • 3 months later...

I recommend you to change your HTML code because I really don't like name-unspecified variables

<form action="" method="post" enctype="multipart/form-data" >
<input type="file" name="img1"/>
<input type="file" name="img2"/>
<input type="file" name="img3"/>
<input type="submit" name="submit" value="Submit"/>
</form>

 

I'm using modified version of a function I found at http://php.net. But I can't remember where is it. So, you could use thins function which I found at http://bg2.php.net/manual/en/function.imagecreatefromjpeg.php (Posted by Ninjabear)

<?php
function resize($img, $thumb_width, $newfilename) 
{ 
  $max_width=$thumb_width;

    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2')) 
    {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }

    //Get Image size info
    list($width_orig, $height_orig, $image_type) = getimagesize($img);
    
    switch ($image_type) 
    {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }
    
    /*** calculate the aspect ratio ***/
    $aspect_ratio = (float) $height_orig / $width_orig;

    /*** calculate the thumbnail width based on the height ***/
    $thumb_height = round($thumb_width * $aspect_ratio);
    

    while($thumb_height>$max_width)
    {
        $thumb_width-=10;
        $thumb_height = round($thumb_width * $aspect_ratio);
    }
    
    $newImg = imagecreatetruecolor($thumb_width, $thumb_height);
    
    /* Check if this image is PNG or GIF, then set if Transparent*/  
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
    
    //Generate the file, and rename it to $newfilename
    switch ($image_type) 
    {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}
//This stuff is outside of the function. It operates with our images
    if(isset($_POST[submit])){
     $imgNumb=1; //This the "pointer" to images
     $DestinationDir="images/";  //Place the destination dir here
     $ThumbDir="images/thumb_";  //Place the thumb dir here

       do{
              $Unique=microtime(); // We want unique names, right?
              $destination=$DestinationDir.md5($Unique).".jpg";
              $thumb=$ThumbDir.md5($Unique).".jpg";

               $IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
              echo resize($_FILES["img$imgNumb"][tmp_name], $IMG[0], $destination);
              $imgNumb++;
         } while($_FILES["img$imgNumb"][name]);
    }
?>

 

Hope this finally works :D

 

the thumbnailing does not work?

 

and on this line  $thumb_width = 10;

there was a - infront of = is this normal?

  • 1 year later...

Thanks for the codes. I am new to php.

I copied the first reply to this post but I kept getting the following error:

PHP Notice: Use of undefined constant submit - assumed 'submit' in c:\inetpub\wwwroot\labennis\admin\uploads.php on line 55

 

my uploads.php code ( which as I said was copied from an earlier post) is:

 

<?php

 

function imgReisize($uploadedfile, $Destination, $Thumb){

//this is the function that will resize and copy our images

 

// Create an Image from it so we can do the resize

$src = imagecreatefromjpeg($uploadedfile);

 

// Capture the original size of the uploaded image

list($width,$height)=getimagesize($uploadedfile);

 

// For our purposes, I have resized the image to be

// 600 pixels wide, and maintain the original aspect

// ratio. This prevents the image from being "stretched"

// or "squashed". If you prefer some max width other than

// 600, simply change the $newwidth variable

$newwidth=600;

$newheight=($height/$width)*600;

$tmp=imagecreatetruecolor($newwidth,$newheight);

 

// this line actually does the image resizing, copying from the original

// image into the $tmp image

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

 

// now write the resized image to disk. I have assumed that you want the

// resized, uploaded image file to reside in the ./images subdirectory.

$filename = $Destination;

imagejpeg($tmp,$filename,100);

 

// For our purposes, I have resized the image to be

// 150 pixels high, and maintain the original aspect

// ratio. This prevents the image from being "stretched"

// or "squashed". If you prefer some max height other than

// 150, simply change the $newheight variable

$newheight=150;

$newwidth=($width/$height)*150;

$tmp=imagecreatetruecolor($newwidth,$newheight);

 

// this line actually does the image resizing, copying from the original

// image into the $tmp image

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

 

// now write the resized image to disk. I have assumed that you want the

// resized, uploaded image file to reside in the ./images subdirectory.

$filename = $Thumb;

imagejpeg($tmp,$filename,100);

 

imagedestroy($src);

imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request

// has completed.

 

echo "Successfully Uploaded: <img src='".$filename."'>";

}

 

    if(isset($_POST[submit])){

    $imgNumb=1; //This the "pointer" to images

    $DestinationDir="./imgs/";  //Place the destination dir here

    $ThumbDir="./imgs/thumbs/";  //Place the thumb dir here

 

      while($_FILES["img".$imgNumb][tmp_name]){

              $Unique=microtime(); // We want unique names, right?

              $destination=$DestinationDir.md5($Unique).".jpg";

              $thumb=$ThumbDir.md5($Unique).".jpg";

              imgReisize($_FILES["img".$imgNumb][tmp_name], $destination, $thumb);

              $imgNumb++;

      }

    }

?>

 

 

I would appreciate if this can be fixed.

Guest
This topic is now closed to further replies.
×
×
  • 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.