Current location: Hot Scripts Forums » Programming Languages » PHP » upload image and create thumb (jpeg/gif/png)

upload image and create thumb (jpeg/gif/png)

Reply
  #1 (permalink)  
Old
Newbie Coder
 
Join Date: Jun 2006
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
upload image and create thumb (jpeg/gif/png)

I found a script, after much googling, which allows a user to upload an image to a server and the script generates a thumb of the image. The only problem is that it only works for jpgs. I couldn't fnd a script that would allow jpgs/gifs/pngs to be upload and resized. What modifications would i need to do to the following script to get to accept pngs/gifs as well as jpegs?

PHP Code:

<?php

       
if(isset($_POST['Submit']))
       {
           
$size 150// the thumbnail height
           
$filedir 'image/'// the directory for the original image
           
$thumbdir 'image/'// the directory for the thumbnail image
           
$prefix 'small_'// the prefix to be added to the original name
           
$maxfile '2000000';
          
$mode '0666';
           
$userfile_name $_FILES['image']['name'];
           
$userfile_tmp $_FILES['image']['tmp_name'];
           
$userfile_size $_FILES['image']['size'];
           
$userfile_type $_FILES['image']['type'];
           if (isset(
$_FILES['image']['name'])) 
           {
               
$prod_img $filedir.$userfile_name;
               
$prod_img_thumb $thumbdir.$prefix.$userfile_name;
               
move_uploaded_file($userfile_tmp$prod_img);
               
chmod ($prod_imgoctdec($mode));
               
$sizes getimagesize($prod_img);
               
$aspect_ratio $sizes[1]/$sizes[0]; 
               if (
$sizes[1] <= $size)
               {
                   
$new_width $sizes[0];
                   
$new_height $sizes[1];
               }else{
                   
$new_height $size;
                   
$new_width abs($new_height/$aspect_ratio);
               }
               
$destimg=ImageCreateTrueColor($new_width,$new_height)
                   or die(
'Problem In Creating image');
               
$srcimg=ImageCreateFromJPEG($prod_img)
                   or die(
'Problem In opening Source Image');
               
ImageCopyResized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
                   or die(
'Problem In resizing');
               
ImageJPEG($destimg,$prod_img_thumb,90)
                   or die(
'Problem In saving');
               
imagedestroy($destimg);
           }
           echo 
'
           <a href="'
.$prod_img.'">
               <img src="'
.$prod_img_thumb.'" width="'.$new_width.'" heigt="'.$new_height.'">
           </a>'
;
       }else{
           echo 
'
           <form method="POST" action="'
.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data">
           <input type="file" name="image"><p>
           <input type="Submit" name="Submit" value="Submit">
          </form>'
;
      }
     
?>
Thanks. If anyone knows to add to the script please let me know or if someone knows of a decent tutorial please post it.

Thanks
Reply With Quote

Featured Marketplace Scripts (view more)

  #2 (permalink)  
Old
pkcidstudio's Avatar
Coding Addict
 
Join Date: Nov 2005
Posts: 332
Thanks: 0
Thanked 0 Times in 0 Posts
http://www.programmingtalk.com/showt...ghlight=upload
bottom script works you will also need 2 other pages to do it. but this is for uploading to a sql database. let me know if you want the other two pices
Reply With Quote
  #3 (permalink)  
Old
Newbie Coder
 
Join Date: Jun 2006
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
thanks pkcidstudio
Reply With Quote
  #4 (permalink)  
Old
pkcidstudio's Avatar
Coding Addict
 
Join Date: Nov 2005
Posts: 332
Thanks: 0
Thanked 0 Times in 0 Posts
as asked for here are the other two pages.
yoou will have to do some editing as far as variables;

<b>preupload.php</b>
PHP Code:

<?php

    
require ("functions.php");
    
session_start();
    
CheckLogin();

    
// initialization
    
$featured_photo_upload_fields "";
    
$photo_upload_fields "";
    
$counter 1;

    
// default number of fields
    
$featured_number_of_fields "1"
    
$number_of_fields "5"

// If you want more fields, then the call to this page should be like, 
// preupload.php?number_of_fields=20

    
if( $_GET['featured_number_of_fields'] )
    
$featured_number_of_fields = (int)($_GET['featured_number_of_fields']);
    
    if( 
$_GET['number_of_fields'] )
    
$number_of_fields = (int)($_GET['number_of_fields']);
    
    
// this is how you select your amount of photos
        
if(isset($_POST['add_fields']))
    {
        
$number_of_fields $_POST['add_fields'];
    }

        
// Category List
        
    
$result mysql_query"SELECT category_id,category_name FROM gallery_category" );
    while( 
$row mysql_fetch_array$result ) )
    {
$photo_category_list .=<<<__HTML_END
    <option value="$row[0]">$row[1]</option>\n
__HTML_END;
    }
    
mysql_free_result$result );    

// Featured Photo Uploading fields
    
while( $counter <= $featured_number_of_fields )
    {
$featured_photo_upload_fields .=<<<__HTML_END
<tr>
    <td>
    <p><b>Featured Photo</b> (make sure this is added first)</p>
         Photo 
{$counter}:
        <input name=' featured_photo_filename[]' type='file' />
    </td>
</tr>
<tr>
    <td>
         Caption:
        <input name='featured_photo_caption[]' type='text' />
    </td>
</tr>
__HTML_END;
    
$counter++;
    }

// Photo Uploading fields

    
while( $counter <= $number_of_fields )
    {


$photo_upload_fields .=<<<__HTML_END
<tr>
    <td>
    <p><b>Photos<b></p>
         Photo 
{$counter}:
        <input name=' photo_filename[]' type='file' />
    </td>
</tr>
<tr>
    <td>
         Caption:
        <input name='photo_caption[]' type='text' />
    </td>
</tr>
__HTML_END;
    
$counter++;
    }

// Final Output
print admin_menu();
//echo date('l dS \of F Y h:i:s A');
echo date('l, d F Y');
echo <<<__HTML_END
<html>
<link rel= "stylesheet" href= "style.css" type= "text/css" />
</head>
    <title>upload Photos</title>
</head>
<body>
<table width='400' border='0' align='left'  class='blackline'>

<!--begin add fields more images-->


<form action="preupload.php" method="post">

<tr>
    <td>
        <select name="add_fields" value="add_fields">
            <option value="0">--</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="40">40</option>
            <option value="80">80</option>
        </select>
        <input type="submit" name="submit" value="Number of Photos to Upload">
    </td>
</tr>
</form>
<!-- stop add fields more images-->

<tr>
    <td>
        <p>&nbsp;</p>
    </td>
</tr>

<!--begin add featured photo -->
<form enctype='multipart/form-data' action='upload.php' method='post' name='upload_form'>

<!--Insert the photo fields here -->
$featured_photo_upload_fields
<!--stop Insert the photo fields here -->

</form>
<!-- stop add featured photo-->

<tr>
    <td>
        <p>&nbsp;</p>
    </td>
</tr>



<!--on release upload images-->
<form enctype='multipart/form-data' action='upload.php' method='post' name='upload_form'>
<tr>
    <td>
            <input type='submit' name='submit' value='Upload Photos' />
    </td>
    
</tr>
<tr>
    <td>
        <b>Select Category</b>
        <select name='category'>
            
$photo_category_list
        </select>
    </td>
</tr>
<!--stop on release upload images-->

<tr>
    <td>
        <p>&nbsp;</p>
    </td>
</tr>

<!--Insert the photo fields here -->
$photo_upload_fields
<!--stop Insert the photo fields here -->


</table>
</form>
</body>
</html>
__HTML_END;

/*

//////////////////
function add_category ($category_name){
mysql_query( "INSERT INTO gallery_category('category_name') VALUES ('".addslashes( $category_name )."' )");
}
//call to add_Category( "Category Name" );

//////////////////
function edit_category ($category_id, $new_name ){
mysql_query( "UPDATE gallery_category SET category_name='".addslashes ($new_name )."' WHERE category_id='".addslashes( $category_id )."'" );
}
// call to edit_category( CATEGORY_ID, "new name");

//////////////////
function delete_Category ( $category_id ){
global $images_dir;
$result = mysql_query( "SELECT photo_filename FROM gallery_photo WHERE photo_category='".addslashes( $category_id )."'" );
while( $row = @mysql_fetch_array( $result ))
{
unlink($imaes_dir."/".$row[0]);
}
mysql_query( "DELETE FROM gallery_photo WHERE photo_category='".addslashes( $category_id )."'");
mysql_query( "DELETE FROM gallery_category WHERE category_id='".addslashes( $category_id )."'" );
}
//call to delete_category( CATEGORY_ID );
*/
?>
<b>upload.php</b>

PHP Code:

<?php

    
require ("functions.php");
    
session_start();
    
CheckLogin();

    
// initialization
    
$result_final "";
    
$featured_result_final "";
    
$counter 0;

    
//  known photo types
    
$known_photo_types = array( 
                        
'image/pjpeg' => 'jpg',
                        
'image/jpeg' => 'jpg',
                        
'image/gif' => 'gif',
                        
'image/bmp' => 'bmp',
                        
'image/x-png' => 'png'
                    
);
    
    
// GD Function List
    
$gd_function_suffix = array( 
                        
'image/pjpeg' => 'JPEG',
                        
'image/jpeg' => 'JPEG',
                        
'image/gif' => 'GIF',
                        
'image/bmp' => 'WBMP',
                        
'image/x-png' => 'PNG'
                    
);

// Fetch the featured photo array sent by preupload.php
$featured_photos_uploaded $_FILES['featured_photo_filename'];

    
// Fetch the photo caption array
    
$featured_photo_caption $_POST['featured_photo_caption'];

    while( 
$counter <= count($featured_photos_uploaded) )
    {
        if(
$featured_photos_uploaded['size'][$counter] > 0)
        {
            if(!
array_key_exists($featured_photos_uploaded['type'][$counter], $known_photo_types))
            {
                
$featured_result_final .= "File ".($counter+1)." is not a photo<br />";
            }
            else
            {
                
mysql_query"INSERT INTO featured_gallery_photos(`featured_photo_filename`, `featured_photo_caption`, `featured_photo_category`) VALUES('0', '".addslashes($featured_photo_caption[$counter])."', '".addslashes($_POST['featured_category'])."')" );
                
$featured_new_id mysql_insert_id();
                
$featured_filetype $featured_photos_uploaded['type'][$counter];
                
$extention $known_photo_types[$featured_filetype];
                
$featured_filename $featured_new_id.".".$extention;

                
mysql_query"UPDATE featured_gallery_photos SET featured_photo_filename='".addslashes($featured_filename)."' WHERE featured_photo_id='".addslashes($featured_new_id)."'" );

                
// Store the orignal file
                
copy($featured_photos_uploaded['tmp_name'][$counter], $featured_images_dir."/".$featured_filename);

                
//Thumbnail size
                
$size GetImageSize$featured_images_dir."/".$featured_filename );
                if(
$size[0] > $size[1])
                {
                    
$thumbnail_width 100;
                    
$thumbnail_height = (int)(100 $size[1] / $size[0]);
                }
                else
                {
                    
$thumbnail_width = (int)(100 $size[0] / $size[1]);
                    
$thumbnail_height 100;
                }
            
                
// Build Thumbnail with GD 2.x.x,
                
$function_suffix $gd_function_suffix[$featured_filetype];
                
$function_to_read "ImageCreateFrom".$function_suffix;
                
$function_to_write "Image".$function_suffix;

                
// Read the source file
                
$source_handle $function_to_read $featured_images_dir."/".$featured_filename ); 
                
                if(
$source_handle)
                {
                    
//blank image for the thumbnail
                         
$destination_handle ImageCreateTrueColor $thumbnail_width$thumbnail_height );
                
                    
// Now we resize it
                      
ImageCopyResampled$destination_handle$source_handle0000$thumbnail_width$thumbnail_height$size[0], $size[1] );
                }

                
// save the thumbnail
                
$function_to_write$destination_handle$featured_images_dir."/tb_".$featured_filename );
                
ImageDestroy($destination_handle );
                
//

                
$featured_result_final .= "<img src='".$featured_images_dir"/tb_".$featured_filename."' /> File ".($counter+1)." Added<br />";
            }
        }
    
$counter++;
    }

    
    
//////////////////////////////////////////////////

    // Fetch the photo array sent by preupload.php
    
$photos_uploaded $_FILES['photo_filename'];

    
// Fetch the photo caption array
    
$photo_caption $_POST['photo_caption'];

    while( 
$counter <= count($photos_uploaded) )
    {
        if(
$photos_uploaded['size'][$counter] > 0)
        {
            if(!
array_key_exists($photos_uploaded['type'][$counter], $known_photo_types))
            {
                
$result_final .= "File ".($counter+1)." is not a photo<br />";
            }
            else
            {
                
mysql_query"INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" );
                
$new_id mysql_insert_id();
                
$filetype $photos_uploaded['type'][$counter];
                
$extention $known_photo_types[$filetype];
                
$filename $new_id.".".$extention;

                
mysql_query"UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" );

                
// Store the orignal file
                
copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename);

                
//Thumbnail size
                
$size GetImageSize$images_dir."/".$filename );
                if(
$size[0] > $size[1])
                {
                    
$thumbnail_width 100;
                    
$thumbnail_height = (int)(100 $size[1] / $size[0]);
                }
                else
                {
                    
$thumbnail_width = (int)(100 $size[0] / $size[1]);
                    
$thumbnail_height 100;
                }
            
                
// Build Thumbnail with GD 2.x.x,
                
$function_suffix $gd_function_suffix[$filetype];
                
$function_to_read "ImageCreateFrom".$function_suffix;
                
$function_to_write "Image".$function_suffix;

                
// Read the source file
                
$source_handle $function_to_read $images_dir."/".$filename ); 
                
                if(
$source_handle)
                {
                    
//blank image for the thumbnail
                         
$destination_handle ImageCreateTrueColor $thumbnail_width$thumbnail_height );
                
                    
// Now we resize it
                      
ImageCopyResampled$destination_handle$source_handle0000$thumbnail_width$thumbnail_height$size[0], $size[1] );
                }

                
// save the thumbnail
                
$function_to_write$destination_handle$images_dir."/tb_".$filename );
                
ImageDestroy($destination_handle );
                
//

                
$result_final .= "<img src='".$images_dir"/tb_".$filename."' /> File ".($counter+1)." Added<br />";
            }
        }
    
$counter++;
    }

    
// Print Result
print admin_menu();
echo <<<__HTML_END
<html>
<link rel= "stylesheet" href= "style.css" type= "text/css" />
</head>
    <title>Photos uploaded</title>
</head>
<body>
    
$featured_result_final
    
$result_final
</body>
</html>

__HTML_END;
?>
<b>viewgallery.php</b>

PHP Code:

<?php

    
require ("functions.php");
    
session_start();
    
CheckLogin();

    
// initialization
    
$result_array = array();
    
$counter 0;

    
$cid = (int)($_GET['cid']);
    
$pid = (int)($_GET['pid']);

    
// Category Listing

    
if( empty($cid) && empty($pid) )
    {
        
$number_of_categories_in_row 1;

        
$result mysql_query"SELECT c.category_id,c.category_name,COUNT(photo_id)
                        FROM gallery_category as c
                        LEFT JOIN gallery_photos as p ON p.photo_category = c.category_id
                        GROUP BY c.category_id" 
);
        while( 
$row mysql_fetch_array$result ) )
        {
            
$result_array[] = "<a href='viewgallery.php?cid=".$row[0]."'>".$row[1]."</a> "."(".$row[2].")";
        }
        
mysql_free_result$result );    

        
$result_final "<tr>\n";

        foreach(
$result_array as $category_link)
        {
            if(
$counter == $number_of_categories_in_row)
            {    
                
$counter 1;
                
$result_final .= "\n</tr>\n<tr>\n";
            }
            else
            
$counter++;

            
$result_final .= "\t<td>".$category_link."</td>\n";
        }

        if(
$counter)
        {
            if(
$number_of_categories_in_row-$counter)
            
$result_final .= "\t<td colspan='".($number_of_categories_in_row-$counter)."'>&nbsp;</td>\n";

            
$result_final .= "</tr>";
        }
    }


    
// Thumbnail Listing

    
else if( $cid && empty( $pid ) )
    {
        
$number_of_thumbs_in_row 5;

        
$result mysql_query"SELECT photo_id,photo_caption,photo_filename FROM gallery_photos WHERE photo_category='".addslashes($cid)."'" );
        
$nr mysql_num_rows$result );

        if( empty( 
$nr ) )
        {
            
$result_final "\t<tr><td>No Category found</td></tr>\n";
        }
        else
        {
            while( 
$row mysql_fetch_array$result ) )
            {
                
$result_array[] = "<a href='viewgallery.php?cid=$cid&pid=".$row[0]."'><img src='".$images_dir."/tb_".$row[2]."' border='0' alt='".$row[1]."' /></a>";
            }
            
mysql_free_result$result );    

            
$result_final "<tr>\n";
    
            foreach(
$result_array as $thumbnail_link)
            {
                if(
$counter == $number_of_thumbs_in_row)
                {    
                    
$counter 1;
                    
$result_final .= "\n</tr>\n<tr>\n";
                }
                else
                
$counter++;

                
$result_final .= "\t<td>".$thumbnail_link."</td>\n";
            }
    
            if(
$counter)
            {
                if(
$number_of_photos_in_row-$counter)
            
$result_final .= "\t<td colspan='".($number_of_photos_in_row-$counter)."'>&nbsp;</td>\n";

                
$result_final .= "</tr>";
            }
        }
    }

    
// Full Size View of Photo
    
else if( $pid )
    {
        
$result mysql_query"SELECT photo_caption,photo_filename FROM gallery_photos WHERE photo_id='".addslashes($pid)."'" );
        list(
$photo_caption$photo_filename) = mysql_fetch_array$result );
        
$nr mysql_num_rows$result );
        
mysql_free_result$result );    

        if( empty( 
$nr ) )
        {
            
$result_final "\t<tr><td>No Photo found</td></tr>\n";
        }
        else
        {
            
$result mysql_query"SELECT category_name FROM gallery_category WHERE category_id='".addslashes($cid)."'" );
            list(
$category_name) = mysql_fetch_array$result );
            
mysql_free_result$result );    

            
$result_final .= "<tr>\n\t<td>
                        <a href='viewgallery.php'>Categories</a> &gt; 
                        <a href='viewgallery.php?cid=
$cid'>$category_name</a></td>\n</tr>\n";

            
$result_final .= "<tr>\n\t<td align='center'>
                    <br />
                    <img src='"
.$images_dir."/".$photo_filename."' border='0' alt='".$photo_caption."' />
                    <br />
                    
$photo_caption
                    </td>
                    </tr>"
;
        }
    }

// Final Output
print admin_menu();
echo <<<__HTML_END

<html>
<head>
    <title>Gallery View</title>
<link rel= "stylesheet" href= "style.css" type= "text/css" />
</head>
<body>
<table width='500' border='0' align='left' class='blackline'>
$result_final        
</table>
</body>
</html>

__HTML_END;
?>
<sql needed>
CREATE TABLE gallery_category(
category_id BIGINT (20) unsigned NOT NULL auto_increment,
category_name VARCHAR (50) NOT NULL default '0',
PRIMARY KEY (category_id),
KEY category_id (category_id)
) TYPE=MyISAM;

CREATE TABLE gallery_photos (
photo_id BIGINT (20) unsigned NOT NULL auto_increment,
photo_filename VARCHAR (25),
photo_caption text,
photo_category BIGINT ((20) unsigned NOT NULL default '0',
PRIMARY KEY (photo_id),
KEY photo_id (photo_id)
) TYPE=MyISAM;
<end sql>

well i hope this helps like i said you will need to do some editing and some variable changes and know sql but i hope this helps email me any additions you put into place i would love to see what you do with it.
Reply With Quote
  #5 (permalink)  
Old
Newbie Coder
 
Join Date: Jun 2006
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
thanks, you don't have specific upload dirs declared do you?
Reply With Quote
  #6 (permalink)  
Old
pkcidstudio's Avatar
Coding Addict
 
Join Date: Nov 2005
Posts: 332
Thanks: 0
Thanked 0 Times in 0 Posts
just to the sql
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
create image from bmp robbydweb PHP 1 01-10-06 03:03 PM
Multiple Image Upload and Text in one go php-learner Script Requests 2 04-28-05 01:42 PM
PHP Script Request DazzlyWorks Script Requests 0 01-16-05 02:23 PM
will pay. php script needed. upload, resize, & email jamjammo Script Requests 4 02-29-04 09:30 PM
Upload image & text to MYSQL --> AT THE SAME TIME? charliedhq PHP 1 02-20-04 03:57 PM


All times are GMT -5. The time now is 04:19 PM.
vBulletin® Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.