Solved

Resize image

Posted on 2012-04-07
5
296 Views
Last Modified: 2012-04-15
I am trying to resize the image.
What is wrong with my code?


<?php  

$folderPath = "path.txt";
$textFile = fopen($folderPath, 'r');
$getPath = fread($textFile, filesize($folderPath));
fclose($textFile);
$req_height = 151;
$req_widt = 250;


$uploadDir  = './'.$getPath.'/';  
 $ava = "uploads/".$_FILES['Filedata']['name'];
 list($width, $height, $type) = @getimagesize($_FILES);
 
 // exit if there is some error when processing the image.
if(!isset($width))
	{
		return "Error_in_processing";
	}
		
//////////////////// to maintain the image proportions /////////////////////////
				if(!($width<=$req_width && $height<=$req_height))
				{
					if(($width/$height)>($req_width/$req_height))
					{
						$newwidth = $req_width;
						$newheight = ($height/$width) * $req_width;
					}
					else
					{
						$newheight = $req_height;
						$newwidth = ($width/$height) * $req_height;
						//echo("hello");
					}
				}
				else
				{
					$newwidth = $width;
					$newheight = $height;
				}	
 
 
 $thumb = imagecreatetruecolor($newwidth, $newheight);
  
// use functions according to the file type, only jpg, gif and png are supported.
			switch ( $type ) 
			{
				case 0:	return "Unsupported_file_format";
						break;		
						
				case 1: $source = imagecreatefromgif($filename);
						break;		
						
				case 2: $source = imagecreatefromjpeg($filename);		
						break;		
			 
				case 3: $source = imagecreatefrompng($filename);		
						break;
				default : return "Unsupported_file_format";	
			}
 
///// Resize the image ////////////////////////////////////////
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
 
 
 
if( $_FILES['Filedata']['error'] == 0 ){  
  
  if( move_uploaded_file( $thumb['Filedata']['tmp_name'], $ava ) ){  
  chmod($ava,0777);
  
  echo 'success';  
  exit();  
  
  }  
  
  }  
  

echo 'error';  
exit();  
  
?>  


	
	
}

Open in new window

0
Comment
Question by:Angha110
5 Comments
 
LVL 20

Expert Comment

by:masnrock
Comment Utility
Does this ever resize your images at all? Better yet, what happens when you try to display the output of what the sizes should be after the process of determining?
0
 
LVL 12

Expert Comment

by:Patricia Siu-Lai Ho
Comment Utility
Hi

this part likes having syntax error


if( $_FILES['Filedata']['error'] == 0 ){  
  
  if( move_uploaded_file( $thumb['Filedata']['tmp_name'], $ava ) ){  
  chmod($ava,0777);
  
  echo 'success';  
  exit();  
  
  }  
  
  }  
  

echo 'error';  
exit();  
  
?>  


	
	
}

Open in new window



?> should be at last sentence.
the if {} seems not closing correctly.

Also line 8

$req_widt = 250;

missing h

should be
$req_width = 250;



Patricia / pslh
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Have a look at this line of code, then read the man page.
list($width, $height, $type) = @getimagesize($_FILES);
http://php.net/manual/en/function.getimagesize.php

As you can see from the online man page, your script needs to pass a string filename to the function.  You would have caught this error if you did not have the @ before the function name.  The @ suppresses messages from the function, and at this point in the application development cycle you really want all the messages.

So my first suggestion would be to add error_reporting(E_ALL) to the top of the script, remove all the @ notations, and run it again to see what happens.  I'll find my teaching example of how to upload and resize an image and I'll post it here for you.  Maybe you can adapt its principles to your application needs.  Best, ~Ray
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
<?php // RAY_upload_and_resize_image.php
date_default_timezone_set('America/Chicago');


// UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE


// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{

    // IS GD INSTALLED AT ALL?
    if (!function_exists("gd_info"))
    {
        if ($display) echo "<br/>GD NOT INSTALLED\n";
        return FALSE;
    }

    // IF GD IS INSTALLED GET DETAILS
    $gd = gd_info();

    // IF DISPLAY IS REQUESTED, PRINT DETAILS
    if ($display)
    {
        echo "<br/>GD DETAILS:\n";
        foreach ($gd as $key => $value)
        {
            if ($value === TRUE)  $value = 'YES';
            if ($value === FALSE) $value = 'NO';
            echo "<br/>$key = $value \n";
        }
    }

    // RETURN THE VERSION NUMBER
    $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
    return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
    // IS GD HERE?
    $gdv = get_gd_info();
    if (!$gdv) return FALSE;

    // GET AN IMAGE THING
    $source = imagecreatefromjpeg("$image");

    // GET THE X AND Y DIMENSIONS
    $imageX = imagesx($source);
    $imageY = imagesy($source);

    // IF NO RESIZING IS NEEDED
    if ($imageX <= $width)
    {
        return FALSE;
    }

    // THE WIDTH IS TOO GREAT - MUST RESIZE
    $tnailX = $width;
    $tnailY = (int) (($tnailX * $imageY) / $imageX );

    // WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
    if ($gdv >= 2)
    {
        // IF GD IS AT LEVEL 2 OR ABOVE
        $target = imagecreatetruecolor($tnailX, $tnailY);
        imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    } else
    {
        // IF GD IS AT A LOWER REVISION LEVEL
       $target = imagecreate($tnailX, $tnailY);
       imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    }
    return $target ;
}
/* ********************************************************************************************* */


// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos    = 'RAY_junk';

// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB

// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
    ?>
    <h2>Upload Photos</h2>

    <!-- NOTE THE USE OF ENCTYPE -->
    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="p" value="1" />
    <!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
    <p>
    Find the photo you want to upload and click the "Upload" button below.
    </p>

    <table cellpadding="1" cellspacing="1" border="0">
    <tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
    <tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
    &nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
    </table>
    </form>

    <?php die();

}

// THERE IS POST DATA - PROCESS IT
else
{
    echo "<h2>Results: Upload Photos</h2>\n";
    echo "<p>\n";

    // SYNTHESIZE THE NEW FILE NAME
    $f_type  = trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
    $f_name  = trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
    $my_new  = getcwd() . '/' . $photos . '/' . $f_name . '.' . $f_type;
    $my_file = $photos  . '/' . $f_name . '.' . $f_type;

    // TEST FOR ALLOWABLE EXTENSIONS (ADD OTHERS AS NEEDED)
    if ($f_type != 'jpg')
    {
        die('Sorry, only JPG files allowed');
    }

    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code != 0)
    {
        $error_message = $errors[$error_code];
        echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
        die('Sorry');
    }

    // MOVE THE FILE INTO THE DIRECTORY
    $overwrite    = $_POST['overwrite'];
    $file_size    = number_format($_FILES["userfile"]["size"]);

    // IF THE FILE IS NEW
    if (!file_exists($my_new))
    {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
        {
            $upload_success = 1;
        }
        else
        {
            $upload_success = -1;
        }
    }
    // IF THE FILE ALREADY EXISTS
    else
    {
        echo "<b><i>$my_file</i></b> already exists.\n";

        // SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($overwrite))
        {
            $upload_success = 0;
        }
        // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        else
        {
            $now    = date('Y-m-d');
            $my_bak = $my_new . '.' . $now . '.bak';
            if (!copy($my_new, $my_bak))
            {
                echo "<b>Attempted Backup Failed!</b>\n";
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
            }
        }
    }

    // REPORT OUR SUCCESS OR FAILURE
    if ($upload_success == 2) { echo "It has been overwritten.\n"; }
    if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
    if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }

    if ($upload_success > 0)
    {
        echo "$file_size bytes uploaded.\n";
        chmod ($my_new, 0755);
    }

    echo "</p>\n";

    // RESIZE THE FILE TO FIT DESIGNATED WIDTH, IF NECESSARY
    if ($upload_success > 0)
    {
        if ($imageblob = create_right_size_image($my_new))
        {
            imagejpeg($imageblob, $my_new);
        }
    }

    echo "<p><a href=\"$my_file\">See the file</a></p>\n";
}

Open in new window

0
 

Author Comment

by:Angha110
Comment Utility
Thank you
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now