Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / XHTML

SWF Image Upload & Crop for PHP using jQuery

3.71/5 (6 votes)
11 Aug 2010GPL31 min read 45.4K   1.9K  
A plugin to upload an image using SWF upload and to crop the uploaded image using jQuery and then save the crop result.

Introduction

Recently, I needed a plugin to upload an image using SWF upload and to crop the uploaded image using jQuery and then save the crop result. I couldn't find this combination, so I've tried to combine these requests: SWF upload, crop with jQuery and PHP.

I've found something about SWF upload here and something about jQuery image crop here. Another request was to limit the upload to one file only, to some specific image types and a specified file size. These requests needed a PHP validation too.

These being said, let’s move on to the requirements:

  • PHP GD Library

Ok, now let’s see the implementation:

  1. Set the JS variables needed in the jQuery and then PHP cropping process:
    PHP
    <?php
    require_once("config.php");
    ?>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    	<meta name="generator" content="http://www.php-code.net" />
    	<title>SWF image upload & crop for php using jQuery</title>
        <script type="text/javascript">
        //<![CDATA[
            var baseURL = "<?php echo BASE_URL;?>";
     
            var jsThumbWidth = "100"; 	//this is the thumb width after 
    				//cropping the original image using jQuery
            var jsThumbHeight= "100"; 	//this is the thumb height after 
    				//cropping the original image using jQuery
            var jsCurrentLargeImageWidth;
            var jsCurrentLargeImageHeight;
     
            var varX1= 0;
            var varY1= 0;
            var varX2= 0;
            var varY2= 0;
            var varW = 0;
            var varH = 0;
        //]]>
        </script>

    –> the “config.php” file contains configuration settings and, for this case, looks like this:

    PHP
    <?php
    define("BASE_URL", "http://demo.php-code.net/swf_upload_and_crop");
    ?> 
  2. Include all necessary files (JS and CSS):
    HTML
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/functions.js"></script>
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/upload/jquery.imgareaselect.js">
    	</script><!-- for jQuery cropping-->
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/upload/purejstemplate_jquery.js">
    	</script> <!-- for loading display-->
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/upload/swfupload.js">
    	</script><!-- for SWF upload-->
    <script type="text/javascript" src="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/js/upload/swfupload.handlers.js">
    	</script><!-- for SWF upload-->
    <link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/css/main.css" />
    <link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/css/upload/imgareaselect-default.css" />
    	<!-- for jQuery cropping-->
    <link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
    	/swf_upload_and_crop/css/upload/swfupload.css" /><!-- for SWF upload-->
  3. Set the configuration for SWF upload:
    JavaScript
    <script type="text/javascript">
            //<![CDATA[
            var swfu;
            window.onload = function() {
                var settings = {
                    flash_url : baseURL + "/media/swfupload.swf",
                    upload_url: baseURL + "/functions.php?upload_user_image",
                    //post_params: {}, 	//if you need to send some parameters like, 
    				//user id, PHP session id, etc
                    file_size_limit : "1 MB", 	//the uploaded file cannot be 
    					//bigger than this limit
                    //debug: true, //if is set to true we can debug 
                    prevent_swf_caching: true,
                    file_types : "*.jpg; *.jpeg; *.gif; *.png",
                    file_types_description: "Multimedia files",
                    //file_upload_limit : 1,
                    //file_queue_limit : 1,
                    file_post_name : 'uploaded_image',
                    custom_settings : {
                        messageTargetId : "message",
                        cancelButtonId : "btnCancel",
                        fileTemplateId : "tplFileQueue",
                        //Good
                        queueContainer : "uploadQueueContainer",
                        queue : {},
                            uploadSessionError : false
                    },
                    // Button settings
                    button_width: "61",
                    button_height: "22",
                    button_placeholder_id: "spanButtonPlaceHolder",
                    button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                    button_cursor: SWFUpload.CURSOR.HAND,
                    // The event handler functions are defined in handlers.js
                    swfupload_loaded_handler : swfUploadLoaded,
                    file_queued_handler : fileQueued,
                    file_queue_error_handler : fileQueueError,
                    file_dialog_complete_handler : fileDialogComplete,
                    upload_start_handler : uploadStart,
                    upload_progress_handler : uploadProgress,
                    upload_error_handler : uploadError,
                    upload_success_handler : uploadSuccess,
                    upload_complete_handler : uploadComplete
                    //queue_complete_handler : queueComplete  // Queue plugin event
                };
                swfu = new SWFUpload(settings);
            };
            //]]>
        </script>
    </head>
  4. Create the HTML template for SWF upload:
    HTML
    <body>
        <h2>SWF image upload & crop for php using jQuery</h2>
        <div id="tplFileQueue" style="display:none;">
            <li id="#?=data.id?#" class="uploadOpen fileQueueItem">
                <div class="items">
                    <strong>#?=data.name?#</strong>
                    <b>#?=data.size?#</b>
                    <b>#?=data.type?#</b>
                    <em id="message">#?=data.message?#</em>
                    <span class="status" >#?=data.status?#</span>
                </div>
            </li>
        </div>
        <div class="pageUpload" id="content">
            <form action="#" id="uploadForm">
                <div class="boxGray">
                    <div class="boxGrayMargin">
                        <div id="spanButtonPlaceHolder"></div>
                        <input id="btnUpload" onclick="alert('da'); return false;" 
    			type="button" value="Browse..." style="width: 61px; 
    			height: 22px; font-size: 8pt;"/>
                        <p>Allowed image size: 1 MB. </p>
                        <p>Allowed extensions: *.jpg; *.jpeg; *.gif; *.png.</p>	
                    </div>
                </div>
                <div id="divLoadingContent"  style="background-color: #FFFF66; 
    		border-top: solid 4px #FF9966; border-bottom: 
    		solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; 
    		display: none;">SWFUpload is loading. Please wait...</div>
                <div id="divLongLoading"  style="background-color: #FFFF66; 
    		border-top: solid 4px #FF9966; border-bottom: 
    		solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; 
    		display: none;">SWFUpload loading failed. 
    		Please check to see if you have Flash activated and a 
    		valid version of Flash Player.</div>
                <div id="divAlternateContent" style="background-color: #FFFF66; 
    		border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966;
    		margin: 10px 25px; padding: 10px 15px; display: none;">
                    Sorry. SWFUpload loading failed.  You must install or 
    			upgrade your Flash Player.
                    Please visit <a href="http://www.adobe.com/shockwave/
    		download/download.cgi?P1_Prod_Version=ShockwaveFlash">
    		Adobe website</a> to download Flash Player.
                </div>
                <ul id="uploadQueueContainer" class="upload"></ul>
                <div class="boxGraySimple" id="footerStatus">
    		<div class="boxGraySimpleTop"><div>&nbsp;
    		</div></div><div class="boxGraySimpleMargin">
                    <div class="message"></div>
                    <div class="submit">
                        <p><span class="btn"><a href="javascript:;" 
    			onclick="save_upload();return false;" id="add_file">
    			SAVE</a></span></p>
                    </div>
                </div><div class="boxGraySimpleBottom"><div>&nbsp;</div></div></div>
            </form>
            <div id="thumbnail"></div>
        </div>
        <script type="text/javascript">
        //<![CDATA[
            $(document).ready(function(){
                $('#thumbnail').imgAreaSelect({show: true,
                                                x1: varX1, 
                                                y1: varY1,
                                                x2: varX2,
                                                y2: varY2,
                                                onSelectChange: showPreview});
            });
         //]]>
        </script>
    </body>
    </html>
  5. The save_upload function is the function that should save the image (is located in “js/upload/swfupload.handlers.js“) if everything is ok and looks like this (you can notice the condition “if(fileContor == 1)” which is used to check how many files we are allowed to upload):
    JavaScript
    function save_upload(){
    	var uploadError = 0;
    	stats 			= swfu.getStats();
     
    	var cropDataString = '';
    	cropDataString += '&x1=' + $('#x1').val();
    	cropDataString += '&y1=' + $('#y1').val();
    	cropDataString += '&x2=' + $('#x2').val();
    	cropDataString += '&y2=' + $('#y2').val();
    	cropDataString += '&w=' + $('#w').val();
    	cropDataString += '&h=' + $('#h').val();
     
    	if(fileContor == 1){
    		$.ajax({
                type: "post",
    			url: baseURL + "/functions.php?save_upload",
    			data: "file_name=" + fileName + cropDataString,
    			cache: false,
    			success: function(msg){
    				msgJSON = JSON.parse(msg);
    				if(msgJSON && typeof(msgJSON.response) 
    				!= 'undefined' && msgJSON.response != 'ok'){
    					if(msgJSON.response == 'error'){
    					alert("The file type is 
    					not within the allowed ones!");
    					}
    					else if(msgJSON.response == 
    					'error_save'){
    					alert("Image could not be saved!");
    					}
    					else if(msgJSON.response == 
    					'error_dates'){
    					alert("2 - No file added!");
    					}
     
    					if(stats.files_queued==0 && 
    						fileContor == 0){
    						uploadError=3;
    					}
     
    					if(uploadError==3){
    						alert('3 - No file added!');
    					}
    				}
    				else if(msgJSON && typeof(msgJSON.response) 
    				!= 'undefined' && msgJSON.response == 'ok'){
                        //here comes your code for saving, I just put a redirect
    					location.href = baseURL + 
    				"/upload_images/" + msgJSON.file_name;
    				}
    				fileContor--;
    			}
    		});
    	}
    	else{
    		alert("1 - No file added!");
    	}
    }

    OBS: I used the old JavaScript alert() function, but I suggest you to use the more beautiful version of this, named jAlert(). You can find some documentation for this here.

History

  • 11th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)