Solved

php image thumbnail upload script

Posted on 2003-11-28
11
8,220 Views
Last Modified: 2007-12-19
hello,
I need a easy tutorial....
I need a script that will allow me to upload an image, then create a thumbnail copy of it, so i then have 2 images, then both names will be inserted into my db.  I have found many scripts like this on the web, but they never seem to be complete
0
Comment
Question by:jblayney
  • 7
  • 4
11 Comments
 
LVL 12

Accepted Solution

by:
mmc98dl1 earned 50 total points
ID: 9840147
http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_20806629.html

you need to ensure you have the latest version of PHP and GD2 installed for this to work.

Duncan
0
 
LVL 1

Author Comment

by:jblayney
ID: 9840206
tx duncan,
I do have the latest php and gd installed, that link you took me to, is not the complete code though, their re include files missing as well as the upload form, so u have anymore information..


justin
0
 
LVL 12

Expert Comment

by:mmc98dl1
ID: 9840273
The include files are simply a login script, and an HTML footer and header file.  They arent of importance to this question.

The form looks like this:

<table class='border' width='75%' align='center'>      
<tr><th>Album Image upload</th></tr>
<tr>
            <td colspan='2' valign='top'>
                  
                  <form action="upload.php" method="post" enctype="multipart/form-data">
                  <table width='100%'>
                  <tr>
                        <th>Name:</th>
                        <th>Description:</th>
                        <th>Gallery:</th>
                        <th>File:</th>
                  </tr>
                  <tr>
                        <td><input type="text" name="name"></td>
                        <td><input type="text" name="description"></td>
                        <td><?php
                        $sql = "SELECT * FROM Album order by AlbumName";
                        dbDo(&$result,$sql);
                  
                        print "<select name=galleryId>\n";
                        while (odbc_fetch_row($result)){
                              print "<option value=".odbc_result($result,1).">".odbc_result($result,2)."\n";
                        }
                        print "</select>\n";

                  ?>      </td>
                        <td><input type="file" name="file" accept="image/jpeg,image/x-png"></td>
                  </tr>
                  <tr>
                        <td><input type="submit" name="action" value="upload"></td>
                  </tr>
                  </table>
                  </form>

            </td>
      </tr>
</table>

This will allow you to have a database of images that fit into albums.

Your Album table looks like this:
AlbumId int
AlbumName varchar
AlbumDescription varchar
DateCreated Datetime default Now()
AlbumFolder

The Image table:
ImageId int
ImageName varchar
ImageDescription varchar
UploadDate datetime default Now()
ImageFile
ThumbnailFile
AlbumId

I think from that you should be able to insert the images, then all you need is to do some SELECT's on it to get the info out.  The AlbumFolder field is the web path NOT the absolute path.
0
 
LVL 1

Author Comment

by:jblayney
ID: 9840461
ok tx again, ( i increased the points, maybe u can help me work through this)
I tried to make your script work with my db, the error i get is "No input file specified. "

This is my code, I renamed the file imageUpload2.php, I changed the upload directory to "uploads/", Its not my server so i have no idea where my site and folder are, I have specified that uploads folder in my php.ini for uploading, and i have other simple upload scripts that work with it.

Also, what will my copied thumb be named ?

<?

     $uploadDir = "uploads/";
     $fileName = $_FILES['file']['tmp_name'];
     $userfileName = str_replace(" ","_",$_FILES['file']['name']);
    move_uploaded_file($fileName, $uploadDir. $userfileName);
     $source = imagecreatefromjpeg($uploadDir. $userfileName);
     $dest = imagecreate(100, 100);
    $system=explode(".",$userfileName);
    if (preg_match("/jpg|jpeg/",$system[1])){
        $src_img=imagecreatefromjpeg($uploadDir. $userfileName);
          echo("jpg");
    }
    if (preg_match("/png/",$system[1])){
        $src_img=imagecreatefrompng($uploadDir. $userfileName);
    }
     $original_x=imageSX($src_img);
    $original_y=imageSY($src_img);
    if ($original_x > $original_y) {
        $thumb_w=100;
        $thumb_h=$original_y*(100/$original_x);
    }
    if ($original_x < $original_y) {
        $thumb_w=$original_x*(100/$original_y);
        $thumb_h=100;
    }
    if ($original_x == $original_y) {
        $thumb_w=100;
        $thumb_h=100;
    }
    $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
     if (preg_match("/png/",$system[1])){
        imagepng($dst_img,$uploadDir."th_".$userfileName);
    } else {
        imagejpeg($dst_img,$uploadDir."th_".$userfileName);
    }
    imagedestroy($dst_img);
    imagedestroy($src_img);

$db_name = "mine";
$table_name = "image_uploads";
$connection = @mysql_connect("localhost", "user", "pass") or die("Problems connecting - Try again");

$db = @mysql_select_db($db_name, $connection) or die("Problems connecting - please try later");
$sql = "INSERT INTO $table_name
(imageID, imageName, imageClientID, imageBlurb, imageDate)
VALUES('', '$filename', '$id', '$uploadBlurb', 'date')";
 
$result =@mysql_query($sql, $connection) or die("Sorry, coudn't execute query - please try later");
echo ("<span>$realName was copied successfully<br><br></span>");
}
}
    
?>
0
 
LVL 12

Expert Comment

by:mmc98dl1
ID: 9840525
Copied thumb will be called th_originalfilename.jpg

Bear in mind this script will only work for jpg or png.


     $uploadDir = "uploads/";


This definately needs to be the absolute path on your server  like the example I had in mine.

You can find this out by running phpinfo(); on your server, then look for the PATH_TRANSLATED entry - this will tell you where your scripts reside, then change it to reflect uploads/.

0
Easy Project Management (No User Manual Required)

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

 
LVL 1

Author Comment

by:jblayney
ID: 9842449
Hello Duncan,
The path-translated path is not as accuarate as yours, it doesnt go right down to the c-drive, but it is pretty long, this what the beginning of my code looks like now (below).. but now Im getting a weird error

Parse error: parse error in /u/j/jeremy/www.website.com/admin/uploadImage2.php on line 3

line 3 being the path
<?

 $uploadDir = "/u/j/jeremy/www.website.com/admin/uploads/";
     $fileName = $_FILES['file']['tmp_name'];
     $userfileName = str_replace(" ","_",$_FILES['file']['name']);
    move_uploaded_file($fileName, $uploadDir. $userfileName);
     $source = imagecreatefromjpeg($uploadDir. $userfileName);
     $dest = imagecreate(100, 100);
    $system=explode(".",$userfileName);
    if (preg_match("/jpg|jpeg/",$system[1])){
        $src_img=imagecreatefromjpeg($uploadDir. $userfileName);
0
 
LVL 1

Author Comment

by:jblayney
ID: 9842642
Ok, everything works great... except one thing. i tried to upload a file that was exactly 100 kb and got this error

Fatal error: Allowed memory size of 8388608 bytes exhausted at (null):0 (tried to allocate 6264 bytes) in /u/j/jeremy/www.website.com/admin/upload.php on line 10

files that are bigger than 100 kb or smaller work, just this one gave me an error,, and thoughts on this...
0
 
LVL 1

Author Comment

by:jblayney
ID: 9842688
after further testing... i have no idea why the 100 kb image didnt work, i opened it in photshop and resaved it as a 300 kb jpg and it still didnt work..

but i have not been able to get any images over 400 kb to create thumbnails, the original will upload, but no thumbnail..

The application i am buiding is because my client wants to upload 1-2 meg files and have them displayed on a page, which is why i need the thumbnails
0
 
LVL 1

Author Comment

by:jblayney
ID: 9843633
tx, it kind of works, i seem to get errors if i try to upload photshop jpg's or jpgs over 1 meg,

Im going to post a new topic called "thumbnail upload server errors" hopefully you can help me.
0
 
LVL 12

Expert Comment

by:mmc98dl1
ID: 9843640
I take it the 100 kb was a jpg?

and does it work ok for a sample of the clients images?

Note - my mistake - this will only work for JPG's I actually removed the PNG stuff from it.

That error (in my experience) comes up when the server has so many threads open it cant do any more.  

Make sure you still have the

    imagedestroy($dst_img);
    imagedestroy($src_img);

outside any if tags, to make sure whatever the outcome it always does this to clear the memory.

If it continues to happen - you might consider creating an image placeholder in memory of a similar size to the one being uploaded, but this is entirely impractical for 1Mb+ images!  it would be ok for a 100k image.

0
 
LVL 1

Author Comment

by:jblayney
ID: 9843695
i posted a new topic for this named
thumbnail upload server errors

this script is entirely erratic, it accepts images and rejects them for no apparant reason, it accepts some 750 kb images and rejects others, It seems to reject any jpg image created by photoshop or fireworks
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

Suggested Solutions

Title # Comments Views Activity
php documentation 4 22
SQL inner join confusion 15 22
two tables one button 11 20
LOAD DATA LOCAL INFILE problem 11 21
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

747 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

13 Experts available now in Live!

Get 1:1 Help Now