Where magic lives

Monday, October 16, 2006

PHP Image Uploader and Manipulator

Recently I created some code to allow users to upload a JPEG image to a website and resize and crop the image afterwards.

Seeing as this sort of feature could be useful on a lot of sites I made the code as general as possible and am releasing the source code here.

Here is a live demo of the utility.

The source code is in a zip file. You provide a new version of the cropper.php file for any place on the site that you wish to use the tool. Here is an example to show the customisation options available:

<?php

 // This script stores temporary image data in the user's session
 session_start(); 
 
 // The dimensions the uploaded image is resized to.
 // (The aspect ratio is maintained and no quality is lost during 
 // the final crop no matter how small you set these values)
 $default_max_width = 640;
 $default_max_height = 480;

 // The size of the image the user will create:
 $cropped_width = 440;
 $cropped_height = 280;

 // A name for the session variable the script will use (must be
 // unique for your domain)
 $unique_session_key = 'imgcropper';

 // A directory that the webserver can create files in, read from
 // and delete files from (the trailing slash is required)
 define('TEMP_DIR','temp/');

 // Before the user uploads their own image they get to play with
 // this one:
 $default_image = 'default.jpg';

 // A semi transparent gif used to create the darkened effect
 // around the edge of the page.
 $border_background = 'screen.gif';
 
 // After the user has chosen the area to crop, the cropped 
 // image is passed to the following function that you must 
 // write your own code for:
 function storeImage($img_id)
 {
  // $img_id is a GD image reference, if you want the actual 
  // JPEG data pass it to imgdata (as below)
  $_SESSION['imgcropper']['cropped'] = imgdata($img_id); 
 }
 // ...then the user is redirected to this page: 
 $redirect_after_crop = 'done.php';

 // All of the code:
 include("cropper-include.php");
 
?>

The reusable file cropper-include.php contains all of the PHP image uploading and resizing logic, along with the HTML, JavaScript and CSS for the page that allows users to upload their image, drag it around, resize it and save it.

My code assumes that users will not upload images that are too large and I use the memory limit setting in my php.ini file to prevent denial of service attacks. You may wish to alter the code to check the size of uploaded images.

Update (7 Feb 2007): I have previously answered peoples questions in comments on the blog post However due to new work commitments I will probably be too busy to continue doing this so I have set up a Google Group at for people to post their questions to and hopefully other users of the script will be able to provide answers.

Labels:

46 Comments:

  • All the arrow keys move the picture in teh opposite direction to which I would expect (UI problem).

    Steve

    By Anonymous Anonymous, At 1:26 pm  

  • amazing!

    By Anonymous NGDK, At 12:38 pm  

  • When I run the utility using the code "exactly as you programmed it" I get the following error message. Do you know why I'm getting this error and how I can fix this?

    Fatal error: Call to undefined function: imagecreatefromjpeg() in c:\program files\easyphp1-8\www\imagecropper\cropper-include.php on line 15.

    Thanks,
    William Watson

    By Anonymous Anonymous, At 2:16 pm  

  • Hi William. Sounds like you don't have the PHP gd extension installed.

    By Blogger David Nicholson, At 3:04 pm  

  • This is exactly what I've been looking for. I needed a simple way a client could upload and resize images to a set size, because they were always uploading HUGE images to the server that took forever to download. PERFECT!

    Thanks, this will save me a lot of headaches...

    By Blogger Brandon, At 11:39 am  

  • hi, first of all, this script rocks! Big up!

    But i have some problems when i want to use it on my own site.

    I can upload the file, but when normally the image would be shown to cut, there's nothing.

    I expanded the size, and then is saw that there where 2 links named:

    function.move-uploaded-file

    what i'm doing wrong?

    greetz
    tom

    By Blogger Potato, At 4:36 am  

  • Potato, you may be using an old version of PHP, is it possible for you to upgrade?

    By Blogger David Nicholson, At 12:47 pm  

  • How do I save the image? What code is needed for that?

    By Blogger sebstof, At 12:18 pm  

  • sebstof, pay attention to this part of my original post:

    // After the user has chosen the area to crop, the cropped
    // image is passed to the following function that you must
    // write your own code for:
    function storeImage($img_id)
    {
    // $img_id is a GD image reference, if you want the actual
    // JPEG data pass it to imgdata (as below)
    $_SESSION['imgcropper']['cropped'] = imgdata($img_id);
    }

    (You must write your own code to do whatever you want with the resulting image. My example stores it in the users session, you may wish to write it to a file, put it in a database, etc.)

    By Blogger David Nicholson, At 10:38 pm  

  • Please write example how to save image to file.

    By Anonymous Anonymous, At 9:08 pm  

  • Saving to a file:

    // After the user has chosen the area to crop, the cropped
    // image is passed to the following function that you must
    // write your own code for:
    function storeImage($img_id)
    {
    // $img_id is a GD image reference, if you want the actual
    // JPEG data pass it to imgdata (as below)
    $fp = fopen('filename.jpg','wb');
    fwrite($fp, imgdata($img_id));
    fclose($fp);
    }

    By Blogger David Nicholson, At 11:38 pm  

  • Hi, i carnt get it to save the images to file! please help me!! this is a very good script, thanks richard

    By Anonymous Anonymous, At 8:19 pm  

  • Richard, have you tried the code in my comment just above yours? What happened?

    By Blogger David Nicholson, At 2:41 pm  

  • How about a quicky tutorial on how to change the image size for the output? i want to start with your GREAT script but output an image arround 140px wide by about 160px high. so how about it???

    Many thanks in advance

    Tim

    By Blogger Mouse, At 8:30 am  

  • Tim, it is as simple as changing:

    // The size of the image the user will create:
    $cropped_width = 440;
    $cropped_height = 280;

    to

    // The size of the image the user will create:
    $cropped_width = 140;
    $cropped_height = 160;

    By Blogger David Nicholson, At 12:31 pm  

  • David... True my friend BUT then the CSS don't work...!

    By Blogger Mouse, At 10:21 pm  

  • Tim, the CSS will be changed automatically using the values that you enter there. If this is not the case for you, can you tell me the URL of where you have installed the script and I will look...

    By Blogger David Nicholson, At 11:04 pm  

  • Dave, thanks mate, in fact to keep the aspect ratio it took a little more work, the CSS needed tweaking, and to get the image to centre on the part i wanted to crop took a little more work and it is by no means perfect yet BUT... i cracked it and it does work very well!!!! i just need to think about saving the image in such a way that my DB can find it... but thats a challenge for tomorrow AM!!!!

    By Blogger Mouse, At 11:53 pm  

  • mail me at trjennings@gmail.com and i'll send you the link to my use of your script...

    By Blogger Mouse, At 11:54 pm  

  • Another brilliant bit of coding, David! Almost exactly what I was looking for, too.

    What would make it perfect for me is to strip away all the controls so that a user uploads a big file (fresh off his digital camera), then hits save - no manipulation required, because the default_max_width/height will already size the image down to a reasonable size! I tried it - uploaded an image, then did nothing but right-click and save! Instant image resizing - VERY cool!

    Now if I could just get you to add in some code for rotating. ;] (Or maybe you could point me in the right direction?)

    By Blogger Donny Bahama, At 1:06 am  

  • I don't know why you didn't make a script where the file image
    will automatically be save on the sever. I also would like to get this type of script with an email meaning when viewers post images I get an email saying there's an image on file nice work though..

    By Anonymous Anonymous, At 8:36 pm  

  • Donny, glad you like the script. As for rotating, for now I will just have to point you in the right direction as I'm quite busy right now. At some point I'll try and come back and add some rotate options to this script.

    By Blogger David Nicholson, At 9:58 pm  

  • Hi, Greta script, just what i wanted:)

    I am trying to place the whole thing in a new window. i want to trim down the background part a bit because i need to confine it all in a window 500x500px

    Is there a way of compressing it all a bit, such as moving the bottom text up a bit?

    Thanks

    By Anonymous GWP, At 10:27 am  

  • GWP,

    Glad you like the script. You can fiddle with the layout by editing the cropper-include file. It is mostly laid out using CSS.

    By Blogger David Nicholson, At 5:21 pm  

  • hey, could you please edit this script to where it would save the cropped file to server?
    i'd be willing to pay for your troubles, please contact me at bilegt[at]arslanstudios.com

    thanks

    By Anonymous Bilegt Arslan, At 1:55 am  

  • Once the image has been cropped and i save iot by right clicking, it will only save as a *.bmp.
    Is there a way to allow it to save as a *.jpg?

    By Anonymous gwp, At 9:23 am  

  • GWP, It is your borwser that wants to save it as a bmp, the data sent by the server is in JPEG format and the borwser is told this in the Content-Type header. You could try editing done.php so that it sends a Content-Disposition header as well and forces a filename to the browser but you should not have to.

    By Blogger David Nicholson, At 6:02 pm  

  • Hello,
    I have installed your code on my web site, it works great :)

    I have the problem of the right click download only offering BMP file types.

    Please can you post the code change to allow JPG downloads as they compress better.


    Also can you post the script to add an "email this image" button to the done.php code.


    Thanx Graeme (cool code:)

    By Anonymous Anonymous, At 10:35 am  

  • If I drag an image so that it doesnt cover one side it produces a black band, can this be changed to white ??



    Thanx Graeme

    By Anonymous Graeme_Smiffy, At 2:48 pm  

  • I have previously answered peoples questions in comments on the blog post However due to new work commitments I will probably be too busy to continue doing this so I have set up a Google Group at for people to post their questions to and hopefully other users of the script will be able to provide answers.

    By Blogger David Nicholson, At 8:49 pm  

  • • Images Tool. This tool is not handling high quality images / high resolution pictures Properly. When you put a high resolution picture into the tool, it shrinks it down, and the picture it produces is low quality. Can you fix this?
    Take a screenshot, such as 1024×768, and attempt to feed it into the image cropper. If I try to either Zoom, or work with the image, I experience a lossy quality. Attempts to zoom in on a resolution capable image produced a blurry pixelated product.
    • Attached is an example image screenshot. Put this image into the image cropper.
    • The image will load zoomed out completely, at a fixed lower resolution…
    • Try to zoom in on the image
    • It will produce a blurry image if you try and zoom

    By Anonymous amol, At 8:31 am  

  • Very nice.

    WHat would i need to add to the code to to let people add multiple lines of text on top of there pic too?

    By Anonymous Anonymous, At 6:21 am  

  • Your php image cropper and manipulater is great! It's so easy for anyone to use. I'd like to pay you for adding code that would allow a user to upload an image and have it placed in a folder on thier site just for photos. Please let me know an amount to send you for that. The images need to be jpg instead of bmp format.

    Another thing that would be nice is another window, perhaps an iframe, that allows you to view and delete any photo from the folder that stores the photos. Can that be done also?

    Thank you for your time,

    Cindy

    Email: dogdesignz@charter.net

    By Blogger Cindy, At 3:57 am  

  • This is just what I was looking for! Would it be impossible to accept more file formats? Perhaps a pdf or eps?

    By Blogger Gavin, At 10:13 pm  

  • Hello David,

    Thank you for this wonderful script.....

    David or anyone else.....

    How do you include the og uploaded photo with the cropped photo on the
    done.php preview page?
    What and where in the script would I have to change to see this?

    I would like to preview the crop with the og uploaded photo next to
    each other....

    Thank you for your help....

    William

    By Blogger Willie, At 4:31 am  

  • Is there a way to use this code with an .eps file.

    By Anonymous Anonymous, At 2:14 am  

  • Once someone has uploaded an image on to my site I would like them to be able to save it and it being saved to my websites database.
    Do think you could write a code on how they could press "save" and store the img uploaded on a websites database. Im having a hard time figuring that out.

    By Anonymous Anonymous, At 2:00 am  

  • david, brilliant bit of coding!!!

    By Anonymous Anonymous, At 8:31 pm  

  • Hi .. thx for your Nice Code.. I've got a problem.. Problem is when I click on Crop and Save it will redirect too done.php But i don't see any picture!... Here is your cropped image : no photo!

    By Anonymous Anonymous, At 10:23 am  

  • Hi David.. I really need your help to adjust this code to my website... Can u contact me on : arash0@yahoo.com
    Thanks in advance.
    By the way the problem is : I cannot change the size of the frame. I mean i have a cell which its size is 170 x 170 and i want every thing in this cell I mean all your code(cropper) in this cell but i cannot.

    By Anonymous arash, At 3:08 pm  

  • Hi!
    Thanx 4 this script !!!!
    i've used it in my site...
    but what abt smaal images like icons ....?
    it will not work.....
    plz reply me after implementation.

    By Blogger Anushka the best, At 11:58 am  

  • Everybody likes the script, but a lot of them have remarks that they are missing extra functionality. There's nothing wrong with doing some programming yourself and using this great script as a solid base, instead of wining that you are missing something.
    Thanks for the great script! I will surely use it on our website, with some of my own additions!

    By Blogger Harm, At 7:51 am  

  • thank you very much for this script. I totally agree with "Harm". I used this as a foundation and added saving to DB functionality. I'll make it evolve more.

    Once again, thank you very much.

    By Anonymous Durga Chowdary, At 8:57 am  

  • Hi David,

    Nice script, however I am having problems with it. It works fine in FireFox and Opera, but IE renders the cropped image as either black, or a very small thumbnail in upper left corner. Google Chrome will not show the cropped image but keeps reloading the cropper screen.

    Joe

    By Anonymous Joe S., At 9:55 am  

  • hi,this code is amazing .really great.This is code what i have to do in my site.

    But,i have a small problem .can u tell when i resizing the image how can i get the x1,x2,y1,y2 values for cropping.

    please can u help on this.i have urgent reqirement

    Thanks,
    Rajkumar

    By Anonymous Anonymous, At 6:01 am  

  • hi,
    This is amazing,awesome great.This is code what i have to do in my site.

    But,i have a small problem .can u tell how can i unregister the sessions.because after cropping i don't want that sessions.

    i tried session_unregister(); but no use.please help me on this.

    By Anonymous sowjanya, At 6:00 am  

Post a Comment

Subscribe to Post Comments [Atom]



<$I18N$LinksToThisPost>:

Create a Link

<< Home