Jump to content

resize and upload photo


jwk811

Recommended Posts

You need to have GD installed on your PHP, do a:

 

echo phpinfo();

 

Scroll down until you see:

gd

 

GD Support enabled

GD Version bundled (2.0.34 compatible)

FreeType Support enabled

FreeType Linkage with freetype

FreeType Version 2.3.9

GIF Read Support enabled

GIF Create Support enabled

JPEG Support enabled

libJPEG Version 6b

PNG Support enabled

libPNG Version 1.2.37

WBMP Support enabled

XBM Support enabled

 

Once you install gd you should be able to use your scripts.

Link to comment
Share on other sites

Not sure if this is helpful but a script I use to upload and resize images into three folders (original, thumb, large) is

<?php

    class imageValidator{
        //assigns $_FILES to short variables
        //constructor automatically runs when you make a new instance of the class, its a fresh copy.
        function __construct($files){
            $this->origfilename = $files['thePhoto']['name'];
            $this->tmpName = $files['thePhoto']['tmp_name'];
            $this->filesize = $files['thePhoto']['size'];
            $this->fileType = $files['thePhoto']['type'];
            $this->error = 0;
            $this->errormess = '';
            if(strlen($_POST['alt'])>0){
                $this->alt = $_POST['alt'];
            }
        }
        
//checks the file size.
        function checkFileSize(){
//set a max file           
            $maxfilesize = '3000000';
            if($this->filesize>$maxfilesize){
                $this->error = 1;
                $this->errormess .= 'Image file is too large.<br />';
            }
              
        } 
        
//checks that it is the correct file extenstion (no docs etc that could break the site)      
        function checkFileExtension(){
        //white list of what is allowed
        $file_types_array=array('jpe','jpg','jpeg','pjpeg','gif','png','JPE','JPG','JPEG','PJPEG','GIF','PNG');
        // get the file extension
        $pos = strpos($this->origfilename,'.');
        $extn = substr($this->origfilename,$pos+1);
            
        if(!in_array($extn,$file_types_array)){
                $this->error = 1;
                $this->errormess .= 'Incorrect extension<br />';
            }
            
        }
        
        function checkMimeType(){
            
            $file_mime_array = array('image/jpeg','image/pjpeg','image/png','image/gif');
            
            if(!in_array($this->fileType,$file_mime_array)){
                $this->error=2;
                $this->errormess .= 'That is the wrong mime type';
            }
            
        }   

//no harmful characters are entered onto the site-file namesthat could break the site       
        function replaceWithUnderscores(){
            
            $this->not = array(' ', '"', '*',',',';',':','{','}','=','+',')','(','&','^','%','$','%23','@','!','`','~','[',']');
            $this->filename = str_replace($not,'_', strtolower(trim($this->origfilename)));
        }
        
        
        function Random_Password($length) {
        global $string;
            $possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            $string = "";
            
            while(strlen($string)<$length) {
                        $pos = rand(1,61);
                $string .= substr($possible_charactors, $pos,1);
            }
            return($string);
        }
        
        
//resize image. sent image width/ height from addphoto.php        
        function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile ){
            $fw = $forcedwidth;
            $fh = $forcedheight;
            $is = getimagesize($sourcefile);
            if( $is[0] >= $is[1] ){
                $orientation = 0;
            }else{
                $orientation = 1;
                $fw = $forcedheight;
                $fh = $forcedwidth;
            }
            if ( $is[0] > $fw || $is[1] > $fh ){
                if( ( $is[0] - $fw ) >= ( $is[1] - $fh ) ){
                    $iw = $fw;
                    $ih = ( $fw / $is[0] ) * $is[1];
                }else{
                    $ih = $fh;
                    $iw = ( $ih / $is[1] ) * $is[0];
                }
                $t = 1;
            }else{
                $iw = $is[0];
                $ih = $is[1];
                $t = 2;
            }
            if ( $t == 1 ){
                $img_src = imagecreatefromjpeg( $sourcefile );
                $img_dst = imagecreatetruecolor( $iw, $ih );
                imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] );
                if( !imagejpeg( $img_dst, $destfile, 90 ) ){
                    exit( );
                }
            }else if ( $t == 2 ){
                copy( $sourcefile, $destfile );
            }
        } //end function resampimagejpg
        
        
    }//end class

?>

 

This form gets sent thePhoto from your form.

<?php
session_start();
ob_start('gz_handler');  
/**
*Allows a user to upload a photo then resizes it (calls functions to) putting it in original, thumb and large folders. 
*This calls functions to check sizes/extensions etc of a file the user has uploaded.
*uploads it into the database
*/

//checks if the user is logged in either by a session or a saved cookie. take them back to login.php if they arent logged in
if(!isset($_SESSION['loggedIn'])){
    $_SESSION['returnTo']=$_SERVER['SCRIPT_NAME'];
    header('location: ../index.php');
    ob_flush();
}

require_once '../../assets/config.php';
require_once '../../assets/DatabaseClass.php';
require_once '../../assets/HtmlClass.php';
require_once '../../assets/FormClass.php';
require_once '../../assets/imageValidator.php';//all this stuff only happens when someone has hit the submit button.


if(isset($_SESSION['userID']) && is_numeric($_SESSION['userID'])){
    $userID = $_SESSION['userID'];
}

$form = new makeForm($dbConArray);
$form->messageArray['alt'] = '* Required';
$form->messageArray['pDescription'] = '* Required';
$form->messageArray['filename'] = '';

if($_POST['submit']){
        //filter data and check it
    $form->storeValues($_POST);
    $form->checkEmpty('alt');
    $form->checkEmpty('filename');
//check files with imagevalidator - size, extension, names...    
    $files = $_FILES;
    $check = new imageValidator($files);
    $check->checkFileSize();//this is checking the file size and if it exceeds it will send an error.
    $check->checkFileExtension();//checking all acceptable types of file extensions 
    $check->checkMimeType();//checks the Mime type.
    $check->replaceWithUnderscores();//gets rid of the bad guys and replaces them with underscores
    //is also giving a nice safe filename.
    $filename = $check->Random_Password(6).'_'.$check->filename;//creates a new variable which is a combination of random characters and an underscore and our clean filename
    
    if($check->error==0){
//upload files to these locations
        $upload_directory = './images/original/';
        $fullname = './images/large/'.$filename;
        $thumbname = './images/thumb/'.$filename;
move_uploaded_file($check->tmpName, $upload_directory.$filename);//moving the file from the temporary folder to the 'original' folder
//make new copies the size we want and put in the correct folders according the the size         
        $check->resampimagejpg(600, 450, $upload_directory.$filename, $fullname);
       $check->resampimagejpg(100, 100, $upload_directory.$filename, $thumbname);
       
       $query = "INSERT INTO tbl_photo (filename, alt, pUserID) VALUES ('$filename', '{$form->clean['alt']}', '$userID')";
        $a = new databaseClass();
        $a->connect($dbConArray);
        $a->query($query);
    }//end if($check->error==0)
}//end of $_POST.

//make the form
$form->openForm('addPhoto', '', 'post', 'multipart/form-data');
$form->makeHiddenField('pUserID',$userID); // needed to pass the galleryID back to this page for the update query.
$form->makeInputRow('alt', 'checkEmpty','Image Description','text');
$form->makeInputRow('thePhoto', '','Image', 'file');
$form->makeHiddenField('MAX_FILE_SIZE', '2000000');
$form->submitButton('Upload');
$form->closeForm();

####presentation####
$title = 'Upload and Edit Photos - First Five Years';
$keywork = 'Upload Add Edit Photos First Five Years Baby Online scrapbook';
$description ='Image uploader that allows you to add a photo on your first five years website';


if(isset($check->error)){
if($check->error > 0){
    echo $check->errormess;
            echo '<br / >Unable to upload File.';
}else if($check->error==0){
            echo 'OK '.$check->origfilename.' has been renamed '.$filename ;
            echo '<br />The image has been successfully uploaded.';
}
}


$b = new makeForm($dbConArray);              //connect to the database
    $displayquery= "SELECT photoID, filename FROM tbl_photo WHERE pUserID = $userID ORDER BY photoID DESC";
    $b->query($displayquery);                          // the query method runs the query and returns $a->result;
    $output = '';                               // somewhere to store all the output as we process it and format it
    $output = '<table class="imageform" >';              
     
    while($row = $b->result->fetch_array(MYSQLI_BOTH)){
        $output .= '<tr>';
            $output .=' <td><img src="images/thumb/'.$row['filename'].'" /></td>';
    $output .= '<td>';
            $output .= $b->formLink('linkdelete','deletephoto.php','photoID', $row['photoID'],'');
            $output .= '</td>';
            $output .= '</tr>'."\n";
    }
    
    $output .= '</table>';

#####CONTENT
$heading ='ADD/ EDIT PHOTOS';
$body = '';
$body .= $form->wholeForm;
$body .= $output;



include ('assets/head.php');
ob_flush();
?>

 

Of course this is my script so it also requires my form class to write the form and other includes from the website etc plus the database...but hopefully you can incoporate the 'imageValidator.php script and the following code to your page:

 

//check files with imagevalidator - size, extension, names...    
    $files = $_FILES;
    $check = new imageValidator($files);
    $check->checkFileSize();//this is checking the file size and if it exceeds it will send an error.
    $check->checkFileExtension();//checking all acceptable types of file extensions 
    $check->checkMimeType();//checks the Mime type.
    $check->replaceWithUnderscores();//gets rid of the bad guys and replaces them with underscores
    //is also giving a nice safe filename.
    $filename = $check->Random_Password(6).'_'.$check->filename;//creates a new variable which is a combination of random characters and an underscore and our clean filename
    
    if($check->error==0){
//upload files to these locations
        $upload_directory = './images/original/';
        $fullname = './images/large/'.$filename;
        $thumbname = './images/thumb/'.$filename;
move_uploaded_file($check->tmpName, $upload_directory.$filename);//moving the file from the temporary folder to the 'original' folder
//make new copies the size we want and put in the correct folders according the the size         
        $check->resampimagejpg(600, 450, $upload_directory.$filename, $fullname);
       $check->resampimagejpg(100, 100, $upload_directory.$filename, $thumbname);

 

Let me know if this helps :D

Link to comment
Share on other sites

Not sure if this is helpful but a script I use to upload and resize images into three folders (original, thumb, large) is

<?php

    class imageValidator{
        //assigns $_FILES to short variables
        //constructor automatically runs when you make a new instance of the class, its a fresh copy.
        function __construct($files){
            $this->origfilename = $files['thePhoto']['name'];
            $this->tmpName = $files['thePhoto']['tmp_name'];
            $this->filesize = $files['thePhoto']['size'];
            $this->fileType = $files['thePhoto']['type'];
            $this->error = 0;
            $this->errormess = '';
            if(strlen($_POST['alt'])>0){
                $this->alt = $_POST['alt'];
            }
        }
        
//checks the file size.
        function checkFileSize(){
//set a max file           
            $maxfilesize = '3000000';
            if($this->filesize>$maxfilesize){
                $this->error = 1;
                $this->errormess .= 'Image file is too large.<br />';
            }
              
        } 
        
//checks that it is the correct file extenstion (no docs etc that could break the site)      
        function checkFileExtension(){
        //white list of what is allowed
        $file_types_array=array('jpe','jpg','jpeg','pjpeg','gif','png','JPE','JPG','JPEG','PJPEG','GIF','PNG');
        // get the file extension
        $pos = strpos($this->origfilename,'.');
        $extn = substr($this->origfilename,$pos+1);
            
        if(!in_array($extn,$file_types_array)){
                $this->error = 1;
                $this->errormess .= 'Incorrect extension<br />';
            }
            
        }
        
        function checkMimeType(){
            
            $file_mime_array = array('image/jpeg','image/pjpeg','image/png','image/gif');
            
            if(!in_array($this->fileType,$file_mime_array)){
                $this->error=2;
                $this->errormess .= 'That is the wrong mime type';
            }
            
        }   

//no harmful characters are entered onto the site-file namesthat could break the site       
        function replaceWithUnderscores(){
            
            $this->not = array(' ', '"', '*',',',';',':','{','}','=','+',')','(','&','^','%','$','%23','@','!','`','~','[',']');
            $this->filename = str_replace($not,'_', strtolower(trim($this->origfilename)));
        }
        
        
        function Random_Password($length) {
        global $string;
            $possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            $string = "";
            
            while(strlen($string)<$length) {
                        $pos = rand(1,61);
                $string .= substr($possible_charactors, $pos,1);
            }
            return($string);
        }
        
        
//resize image. sent image width/ height from addphoto.php        
        function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile ){
            $fw = $forcedwidth;
            $fh = $forcedheight;
            $is = getimagesize($sourcefile);
            if( $is[0] >= $is[1] ){
                $orientation = 0;
            }else{
                $orientation = 1;
                $fw = $forcedheight;
                $fh = $forcedwidth;
            }
            if ( $is[0] > $fw || $is[1] > $fh ){
                if( ( $is[0] - $fw ) >= ( $is[1] - $fh ) ){
                    $iw = $fw;
                    $ih = ( $fw / $is[0] ) * $is[1];
                }else{
                    $ih = $fh;
                    $iw = ( $ih / $is[1] ) * $is[0];
                }
                $t = 1;
            }else{
                $iw = $is[0];
                $ih = $is[1];
                $t = 2;
            }
            if ( $t == 1 ){
                $img_src = imagecreatefromjpeg( $sourcefile );
                $img_dst = imagecreatetruecolor( $iw, $ih );
                imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] );
                if( !imagejpeg( $img_dst, $destfile, 90 ) ){
                    exit( );
                }
            }else if ( $t == 2 ){
                copy( $sourcefile, $destfile );
            }
        } //end function resampimagejpg
        
        
    }//end class

?>

 

This form gets sent thePhoto from your form.

<?php
session_start();
ob_start('gz_handler');  
/**
*Allows a user to upload a photo then resizes it (calls functions to) putting it in original, thumb and large folders. 
*This calls functions to check sizes/extensions etc of a file the user has uploaded.
*uploads it into the database
*/

//checks if the user is logged in either by a session or a saved cookie. take them back to login.php if they arent logged in
if(!isset($_SESSION['loggedIn'])){
    $_SESSION['returnTo']=$_SERVER['SCRIPT_NAME'];
    header('location: ../index.php');
    ob_flush();
}

require_once '../../assets/config.php';
require_once '../../assets/DatabaseClass.php';
require_once '../../assets/HtmlClass.php';
require_once '../../assets/FormClass.php';
require_once '../../assets/imageValidator.php';//all this stuff only happens when someone has hit the submit button.


if(isset($_SESSION['userID']) && is_numeric($_SESSION['userID'])){
    $userID = $_SESSION['userID'];
}

$form = new makeForm($dbConArray);
$form->messageArray['alt'] = '* Required';
$form->messageArray['pDescription'] = '* Required';
$form->messageArray['filename'] = '';

if($_POST['submit']){
        //filter data and check it
    $form->storeValues($_POST);
    $form->checkEmpty('alt');
    $form->checkEmpty('filename');
//check files with imagevalidator - size, extension, names...    
    $files = $_FILES;
    $check = new imageValidator($files);
    $check->checkFileSize();//this is checking the file size and if it exceeds it will send an error.
    $check->checkFileExtension();//checking all acceptable types of file extensions 
    $check->checkMimeType();//checks the Mime type.
    $check->replaceWithUnderscores();//gets rid of the bad guys and replaces them with underscores
    //is also giving a nice safe filename.
    $filename = $check->Random_Password(6).'_'.$check->filename;//creates a new variable which is a combination of random characters and an underscore and our clean filename
    
    if($check->error==0){
//upload files to these locations
        $upload_directory = './images/original/';
        $fullname = './images/large/'.$filename;
        $thumbname = './images/thumb/'.$filename;
move_uploaded_file($check->tmpName, $upload_directory.$filename);//moving the file from the temporary folder to the 'original' folder
//make new copies the size we want and put in the correct folders according the the size         
        $check->resampimagejpg(600, 450, $upload_directory.$filename, $fullname);
       $check->resampimagejpg(100, 100, $upload_directory.$filename, $thumbname);
       
       $query = "INSERT INTO tbl_photo (filename, alt, pUserID) VALUES ('$filename', '{$form->clean['alt']}', '$userID')";
        $a = new databaseClass();
        $a->connect($dbConArray);
        $a->query($query);
    }//end if($check->error==0)
}//end of $_POST.

//make the form
$form->openForm('addPhoto', '', 'post', 'multipart/form-data');
$form->makeHiddenField('pUserID',$userID); // needed to pass the galleryID back to this page for the update query.
$form->makeInputRow('alt', 'checkEmpty','Image Description','text');
$form->makeInputRow('thePhoto', '','Image', 'file');
$form->makeHiddenField('MAX_FILE_SIZE', '2000000');
$form->submitButton('Upload');
$form->closeForm();

####presentation####
$title = 'Upload and Edit Photos - First Five Years';
$keywork = 'Upload Add Edit Photos First Five Years Baby Online scrapbook';
$description ='Image uploader that allows you to add a photo on your first five years website';


if(isset($check->error)){
if($check->error > 0){
    echo $check->errormess;
            echo '<br / >Unable to upload File.';
}else if($check->error==0){
            echo 'OK '.$check->origfilename.' has been renamed '.$filename ;
            echo '<br />The image has been successfully uploaded.';
}
}


$b = new makeForm($dbConArray);              //connect to the database
    $displayquery= "SELECT photoID, filename FROM tbl_photo WHERE pUserID = $userID ORDER BY photoID DESC";
    $b->query($displayquery);                          // the query method runs the query and returns $a->result;
    $output = '';                               // somewhere to store all the output as we process it and format it
    $output = '<table class="imageform" >';              
     
    while($row = $b->result->fetch_array(MYSQLI_BOTH)){
        $output .= '<tr>';
            $output .=' <td><img src="images/thumb/'.$row['filename'].'" /></td>';
    $output .= '<td>';
            $output .= $b->formLink('linkdelete','deletephoto.php','photoID', $row['photoID'],'');
            $output .= '</td>';
            $output .= '</tr>'."\n";
    }
    
    $output .= '</table>';

#####CONTENT
$heading ='ADD/ EDIT PHOTOS';
$body = '';
$body .= $form->wholeForm;
$body .= $output;



include ('assets/head.php');
ob_flush();
?>

 

Of course this is my script so it also requires my form class to write the form and other includes from the website etc plus the database...but hopefully you can incoporate the 'imageValidator.php script and the following code to your page:

 

//check files with imagevalidator - size, extension, names...    
    $files = $_FILES;
    $check = new imageValidator($files);
    $check->checkFileSize();//this is checking the file size and if it exceeds it will send an error.
    $check->checkFileExtension();//checking all acceptable types of file extensions 
    $check->checkMimeType();//checks the Mime type.
    $check->replaceWithUnderscores();//gets rid of the bad guys and replaces them with underscores
    //is also giving a nice safe filename.
    $filename = $check->Random_Password(6).'_'.$check->filename;//creates a new variable which is a combination of random characters and an underscore and our clean filename
    
    if($check->error==0){
//upload files to these locations
        $upload_directory = './images/original/';
        $fullname = './images/large/'.$filename;
        $thumbname = './images/thumb/'.$filename;
move_uploaded_file($check->tmpName, $upload_directory.$filename);//moving the file from the temporary folder to the 'original' folder
//make new copies the size we want and put in the correct folders according the the size         
        $check->resampimagejpg(600, 450, $upload_directory.$filename, $fullname);
       $check->resampimagejpg(100, 100, $upload_directory.$filename, $thumbname);

 

Let me know if this helps :D

tytyty :D
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.