Jump to content

Image Resize (change main pic and create a thumbnail)


coolphpdude

Recommended Posts

Hi, ive written a great upload script which works fine. It allows a user to upload a pic. what i actually want to happen is when a user uploads any pic regardless of size (a pic of 1600 x 1200 pixels for example) the pic will be resized to 400px width and 250px height and also a thumbnail created of 100px width by 100px height and thn uploaded to a certain path. ive included my code below...

 

		if ((($_FILES["uploadedfile"]["type"] == "image/pjpeg")
		|| ($_FILES["uploadedfile"]["type"] == "image/jpeg")
		|| ($_FILES["uploadedfile"]["type"] == "image/png")
		|| ($_FILES["uploadedfile"]["type"] == "image/bmp"))
		&& ($_FILES["uploadedfile"]["size"] < 2000000))
		{

			// Where the file is going to be placed
			$orig_path = "$username/folder/";
			$target = "$username/folder/";

			/* Add the original filename to our target path.  
			Result is "$username/filename.extension" */
			$target = $target . basename( $_FILES['uploadedfile']['name']); 
			$_FILES['uploadedfile']['tmp_name']; 


			if (file_exists($target))
			{

			// make the random file name
			$rand = md5(rand() * time());
			$target = $orig_path . $rand . basename( $_FILES['uploadedfile']['name']);

				if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target)) 
				{
				$upload="UPDATE user SET user_pic='$target' WHERE username='$user_id'";

					if (mysql_query($sql)) 
					{
						echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
					}
					else
					{
						do_error("could not be added");
					}
				} 
				else
				{
				echo "There was an error uploading the file, please try again!";
				}

			}
			else
			{
				if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
				{
				$upload="UPDATE user SET user_pic='$target' WHERE username='$user_id'";

					if (mysql_query($upload)) 
					{
						echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
					}
					else
					{
						do_error("could not be added");
					}
				} 
				else
				{
				echo "There was an error uploading the file, please try again!";
				}
			}

 

Also, im having trouble uploading png, it says invalid file type so if anyone spots the reason for that error let me know.

 

thanks

Link to comment
Share on other sites

First you need a function to create the thumb and resize the image. Here is a script I have to upload multiple images and resize and save them. You can change the code to suit your needs. If you need help let me know.

 

<?php
$absolute_path = "path/to/image/folder/"; //Absolute path to where files are uploaded make sure ends with slash "/'
$thumb_path = "path/to.thumb/folder/";  //Absolute path to where thumbs are to be stored if you want this make sure ends with slash "/'
$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 = "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>";
?>
<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];
  $file_size = $_FILES["pictures"]['size'][$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{
          // first move the file to
          move_uploaded_file($file, $absolute_path.$file_name);
          // Save full size image with max width/height of 800
          resampleimage("800", $absolute_path.$file_name, $absolute_path.$file_name, 0);
          // Save thumb image with max width/height of 200
          resampleimage("200", $absolute_path.$file_name, $thumb_path.$file_name, 0);
          }
        }
      }
    }
  $i++;
  echo $endresult."<br>";
  }
}
?>

 

This will not resize images that are smaller than the maxsize. If you want it to do that let me know

 

Ray

 

 

Link to comment
Share on other sites

i am quite new to php so that confused me quite a bit. Sorry! I tried following it but i just get lost off. Is there away you could tell me what i would need to fit into my existing code?

 

i really do appreciate your help mate, im a little stuck with this one!

Link to comment
Share on other sites

No problem. first let me ask you this.

 

Do you want to resize smaller images to a larger size or do you want to keep them their original size and create a thumbnail?

 

Also do you want a static width and height, which would stretch images that are not at that aspect ratio, or keep the original aspect ratio?

 

Ray

Link to comment
Share on other sites

Well you really didn't answer my questions but here is some code for you. I implemented it into your code.

 

First you need to copy and past this in your script, preferably at the top. It is a function so nothing is outputed to the browser.

 

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;
  }
}

 

The replace your existing code with this

 

if ((($_FILES["uploadedfile"]["type"] == "image/pjpeg")
		|| ($_FILES["uploadedfile"]["type"] == "image/jpeg")
		|| ($_FILES["uploadedfile"]["type"] == "image/png")
		|| ($_FILES["uploadedfile"]["type"] == "image/bmp"))
		&& ($_FILES["uploadedfile"]["size"] < 2000000))
		{

			// Where the file is going to be placed
			$i_dest = "$username/images/";
        $t_dest = "$username/images/thumbs/";

			if (file_exists($target))
			{

			// make the random file name
			$rand = md5(rand() * time());
			$img_dest = $i_dest . $rand . basename( $_FILES['uploadedfile']['name']);
        $th_dest = $t_dest . $rand . basename( $_FILES['uploadedfile']['name']);

				if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $img_dest))
				{
				$upload="UPDATE user SET user_pic='$target' WHERE username='$user_id'";
          // Save full size image with max width/height
          resampleimage("800", $img_dest, $img_dest, 0);
          // Save thumb image with max width/height of 200
          resampleimage("200", $img_dest, $th_dest, 0);

					if (mysql_query($sql))
					{
						echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
					}
					else
					{
						do_error("could not be added");
					}
				}
				else
				{
				echo "There was an error uploading the file, please try again!";
				}

			}
			else
			{
				if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
				{
			  $img_dest = $i_dest . basename( $_FILES['uploadedfile']['name']);
          $th_dest = $t_dest .  basename( $_FILES['uploadedfile']['name']);

				$upload="UPDATE user SET user_pic='$target' WHERE username='$user_id'";
          // Save full size image with max width/height of 400
          resampleimage("400", $img_dest, $img_dest, 0);
          // Save thumb image with max width/height of 100
          resampleimage("100", $img_dest, $th_dest, 0);
					if (mysql_query($upload))
					{
						echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
					}
					else
					{
						do_error("could not be added");
					}
				}
				else
				{
				echo "There was an error uploading the file, please try again!";
				}
			}

 

Ray

 

 

Link to comment
Share on other sites

hi ray, im just about to give this a go. after thinking about it i would prefer to keep the aspect ratio once the image has been resized. will this allow me to do that?

 

so for example i set a width to resize the image but the height is determined by the aspect of the original, so if it was orinally 1600x1200 and i want the new pic to only be 160 width it would automatically adjust the height to 120. (i have only used these figures for the easy math, i actually want the width of the main picture to be 400pixels).

 

Cheers

Link to comment
Share on other sites

This will keep the aspect ratio. But if a picture is say 800X1600 and you set the maxsize at 400 the picture will become 200x400 to maintain the aspect ratio. This will only be like that if a picture is a lot higher than it is wider.

 

the maxsize is for both the width and the height. so whichever is greater that will become the maxsize and the other will be adjusted to maintain the aspect ratio.

 

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.