Hi

I have a function 'checkfile'within my 'add a record'form which checks to ensure that the images which users are uploading with the form are within a certain size...in this case 32kb, which is specified within GW_MAXFILESIZE.

What would actually be much more useful and user friendly is if when the user selects an image from their desktop, the image is automatically resized to 32kb?

Does anyone know how to do this?

function checkfile($image_name,$type,$size,$tmp_name,$error)
{
	
	$output ='start';

	if (!empty($image_name)) 
	   {
      if (
	  (($type == 'image/gif') || ($type == 'image/jpg') || ($type == 'image/pjpeg') || ($type == 'image/png') || ($type == 'image/jpeg'))
	  && (($size > 0) && ($size <= GW_MAXFILESIZE))
		  && ($error == '0'))
	  {
        // Move the files to the target upload folder
          $target = GW_UPLOADPATH . $image_name;
		  if (move_uploaded_file($tmp_name , $target) ) {$output = 'success';} else {$output = 'load error'; }
	  } 
	  else { $output='error'; }
	   }
	  else { $output='success'; }

	return $output;
}

This is the check which is then carried out to confirm that images are the size they are meant to be:

$image_main_check = checkfile($image_main_name,$_FILES['image_main']['type'],$_FILES['image_main']['size'],$_FILES['image_main']['tmp_name'],$_FILES['image_main']['error']) ;

If the images are too large - then a straightforward error message is displayed telling them this and to go and resize and try again....

Ideally I would like the check to happen and if the images are too large (which they probably all would be as this is a small size), then for a bit of code to automatically resize them?

This would really be the icing on the cake of this website :-)

Many thanks for any help which can be offered....

Size and width/height are two different things, you can have an image of 800x600 and 1.2MB and another of the same width and height but only 200KB, depends on colors, on format and compression.

So, if the user is uploading a file of 800KB, you can't be sure that with a simple resize the output will be a file of 32KB.

You should just check if the file has the sizes you want, and if not, then the user should change the values on his own computer, because converting/resizing images can be a really CPU expensive process. If you don't use a load balancer like Gearman, then few users running the same script, at the same time, can kill the server.

My Opinion. Bye :)

You should just check if the file has the sizes you want, and if not, then the user should change the values on his own computer

This is perfect solution. That should be "policy". User should not upload files greater than you want them to :)

Hi. Well this is what I currently have, which I might add works very well :-) i.e. for the user to resize their own images.

However my manager would like the site to be like 'facebook', 'ebay'etc where the user just selects their pictures and the resizing is done for them. As mentioned more concered with the file size rather than the actual dimensions.

Does the $getimagesize function do this?

many thanks

Member Avatar for iamthwee

TimThumb is the answer.

Hi
Well I'm still plugging away trying to achieve auto-resizing on images.

I've progressed a little bit...

Here is my php page as above but with an additional variable $reductionfactor added to the function checkfile.

GW_MAXFILESIZE specifies a size limit of 32kb.

<?php require_once('Connections/dreamsin_localhost.php'); 
      require_once('myaccess/appvars.php');

// Connect to the database
  $dbc = mysqli_connect("localhost", "xxxxxxxxx", "xxxxxxxxxx", "xxxxxxxxxxxx");

function createfilename($ID,$image_name)
{

	if (!empty($image_name)) 
	{
	$output = number_format($ID,0,".",",") . '_' . time() . '_' . mt_rand() .$image_name;
	return $output;
	}
	else
	{
	$output = "";
	}
}

function checkfile($image_name,$type,$size,$tmp_name,$error)
{
	
	$output ='start';

	if (!empty($image_name)) 
	   {
      if (
	  (($type == 'image/gif') || ($type == 'image/jpg') || ($type == 'image/pjpeg') || ($type == 'image/png') || ($type == 'image/jpeg'))
	  && (($size > 0) && ($size <= GW_MAXFILESIZE))
		  && ($error == '0'))
	  {
        // Move the files to the target upload folder
          $target = GW_UPLOADPATH . $image_name;
		  if (move_uploaded_file($tmp_name , $target) ) {$output = 'success';} else {$output = 'load error'; }
	  } 
	  elseif ($size > GW_MAXFILESIZE){ 

 		$target1 = GW_UPLOADPATH . 'original' . $image_name  ;
       	$target2 = GW_UPLOADPATH . $image_name  ;

// leave this line in if you want to keep original 
//     	if (move_uploaded_file($tmp_name , $target1) ) {$output = 'success';} else {$output = 'load error'; }

		$reductionfactor = number_format((GW_MAXFILESIZE / $size)*100,0,'.','');

		include('SimpleImage.php');
		$image = new SimpleImage();
	   	$image->load($tmp_name);
   		$image->scale($reductionfactor);
   		$image->save($target2);
     
	  	$output='success'; 
		
	   }
	  else { $output='error'; }
	   }
	  else { $output='success'; }

	return $output;
}


  if (isset($_POST['submit'])) {
    // Grab the profile data from the POST
    
	$screenpath = "images/propertyimages/";
	$image_main_name = mysqli_real_escape_string($dbc, trim($_FILES['image_main']['name']));
	
	
	$image_main_name = createfilename($_SESSION[ID],$_FILES['image_main']['name']);
	$image_main_check = checkfile($image_main_name,$_FILES['image_main']['type'],$_FILES['image_main']['size'],$_FILES['image_main']['tmp_name'],$_FILES['image_main']['error']) ;
	
	   
	  if ($image_main_check == 'success') 
		  {
	
   
// Connect to the database
  $dbc = mysqli_connect("localhost", "dreamsin", "126XsM3vhh", "dreamsin_property");	

 $query = "INSERT INTO test_imagesize
VALUES (0, '$screenpath', '$image_main_name')";

SimpleImage.php - this is a piece of code I found on the web and seems the author has expressly said it can be copied and used :-)
Attached below for information:

<?php
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=100, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}
?>

In my $reductionfactor variable I've been trying to play around a bit in order to get images to resize consistently, in proportion and within 32kb.

I'm having the following problems:

The images are either resizing to a very small size of 4kb - and then dont'look as clear as they could on the web.
The images are downsizing (if starting of very large) - but still above 32kb.
Some .jpg - it doesn't like at all and I get an error message regarding lines in the SimpleImage.php. - but sometimes it will take a .jpg.

I believe that the main line is:

$reductionfactor = number_format((GW_MAXFILESIZE / $size)*100,0,'.','');

But I've been altering the $size and *100 to different degrees - but still getting the same issues as above...

Any help or suggestions would be fantastic!!

Many thanks

It's late and I still think to let users figure how to match limits but, I was reading imagemagick docs and found this: -define jpeg:extent={size} You can use it like this:

convert -define jpeg:size=900x900 -define jpeg:extent=32kb -thumbnail 450x450 -quality 95 IMG_7070.jpg test_50_b.jpg

This command will rewrite the thumbnail changing quality until it matches the right sizes. It will slow down respect to normal converting but it's not too heavy. The first define it's used to increase speed, you can set it at the same size of the thumbnail -define jpeg:size=450x450 , but I prefer an higher value, it will give a better quality.

Bye :)

Source: http://www.imagemagick.org/Usage/formats/#jpg_write

Hi Yes that would work - except I've only been using the GD Library. But you just reminded me that I have actually resolved this and it can now be closed.

So for anyone needing the answer - after my initial createfilename and checkfile functions I have put the following which works beautifully: Here is the entire code:

function createfilename($ID,$image_name)
{

	$output = "Start";

	if (!empty($image_name)) 
	{
	$output = number_format($ID,0,".",",") . '_' . time() . '_' . mt_rand() .$image_name;
	}
	else
	{
	$output = "No Image";
	}

	return $output;

}

function checkfile($image_name,$type,$size,$tmp_name,$error,$old_width,$old_height)
{
	
	$output ='start';
	$minheight = 200;
	$minwidth = 280;

      	if ($error != 0 ) 
		{
		  $output = 'error-load' ;
		  return $output; 
	  	} 
      	elseif ($type != 'image/gif' && $type != 'image/jpg' && $type != 'image/pjpeg' && $type != 'image/png' && $type != 'image/jpeg' ) 
	  	{
		  $output = 'error-validation' ;
		  return $output; 
	  	}
	  	
      else 
    	{
			// Resize then move the files to the target upload folder
			$target1 = GW_UPLOADPATH . 'original' . $image_name  ;
       		$target2 = GW_UPLOADPATH . $image_name  ;

			// leave this line in if you want to keep original 
			//     	if (move_uploaded_file($tmp_name , $target1) ) {$output = 'success';} else {$output = 'load error'; }

		    if ($size <= GW_MAXFILESIZE ) {$reductionfactor = 1; } else {$reductionfactor =   sqrt ( $size / GW_MAXFILESIZE )  ;}

			$new_height = number_format( $old_height / $reductionfactor ,0 , '.', '');
			$new_width = number_format( $old_width / $reductionfactor ,0 , '.', '');

			// check image dimensions and resize so height and width are greater than our minimum requirement. if they are not then
			// we need to rescale to bring eith the width or height up to minimum requirements
			$new_height_orig = $new_height;$new_width_orig=$new_width;

			if ($new_height < $minheight && $new_width >= $minwidth)
			{
				$new_width = ($minheight/$new_height)*$new_width;
				$new_height = $minheight;
			}
			elseif ($new_height >= $minheight && $new_width < $minwidth)
			{
				$new_height = ($minwidth/$new_width)*$new_height;
				$new_width = $minwidth;
			}
			elseif ($new_height < $minheight && $new_width < $minwidth && $new_height > $new_width)
			{
				$new_height = ($minwidth/$new_width)*$new_height;
				$new_width = $minwidth;
			}
			elseif ($new_height < $minheight && $new_width < $minwidth && $new_height < $new_width)
			{
				$new_width = ($minheight/$new_height)*$new_width;
				$new_height = $minheight;
			}

			// now resize to these dimensions

		    $new_image = imagecreatetruecolor($new_width, $new_height);

	        if(( $type == 'image/jpg'  )|| ($type == 'image/pjpeg')   || ($type == 'image/jpeg')){
				$old_image = imagecreatefromjpeg($tmp_name);
	    		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); 
	 			imagejpeg($new_image,$target2,85);  }
	        elseif( $type == 'image/gif'  ) {
				$old_image = imagecreatefromgif($tmp_name);
	    		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); 
	 			imagegif($new_image,$target2);  }
	        elseif( $type == 'image/png'  ) {
				$old_image = imagecreatefrompng($tmp_name);
	    		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); 
	 			imagepng($new_image,$target2);  }
	
		  	$output='success';
			return $output; 

		 }
		   
	return $output;
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.