SWF image upload & crop for php using jQuery

Recently I’ve 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
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
define("BASE_URL", "http://demo.php-code.net/swf_upload_and_crop");
?>

2.  Include all necessary files (js and css)

<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

<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 can not 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

<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 are we allowed to upload):

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(). Some documentation for this you can find here.

Here you can find the scripts used in this article.

Also, you can try a demo here.

No related posts.

7 Responses to “SWF image upload & crop for php using jQuery”

  1. antony says:

    on the following line

    <script type="text/javascript" src="/swf_upload_and_crop/js/functions.js”>

    where are you getting functions.js? (is it a standard file?)

  2. Claudia says:

    Hi Antony,

    “/swf_upload_and_crop/js/functions.js” is a “homemade” file containing js functions. I created this file to split somehow, the html from js functions, because as you may now you can use the js functions directly in your html code, using an

  3. Mauro says:

    Hello!
    I had a problem when I change the config.php file.
    swap the base url and put the url of my site in the appropriate folder
    when I load a file, when the progress bar ends, you get this error:
    “Error while trying yo comunicate with the server!”

    any ideas?
    the site is:
    http://www.snappminds.com/mauro/php_template_3/TO_DO/swf_upload_and_crop/swf_upload_and_crop/

    Very good all and thanks

  4. Claudia says:

    Hi,

    Probably there is something wrong in the paths you are using. Check them.

  5. chandresh says:

    hello
    i m facing a problem
    when i downloading ur code in my local then changing the base url to my directory then i m getting error regarding file can’t to be upload
    for permissions. and all my permissions are set to 777 so how to do this
    its urgent

  6. Phillip says:

    Hello,

    there is a problem if i need 750×530 size. Thumb show good, but select area is proportional. Is it possible to change?

  7. Merv Forney says:

    Was having a problem with the server i a shared host environment returning a server 412 error. Was advised to put the following in .htaccess:

    SetEnvIfNoCase Content-Type \
    “^multipart/form-data;” “MODSEC_NOPOSTBUFFERING=Do not buffer file uploads”

    Success! Fixed the problem.

Leave a Reply