Flash AS3 Externally Load Multiple Images And Display In Order

Let’s say you want to load 5 images into your Flash app externally, and display them in the same order you loaded them. In AS3 loading external assets happens asychronously, so just because you started a load first doesn’t mean it will be the first to finish. So, if you want to display your images in the order that you load them, you’ll need to do a little work. Here’s a way of doing it:

package  {

	import flash.display.MovieClip;
	import flash.net.URLLoader
	import flash.net.URLRequest
	import flash.events.*;
	import flash.errors.*;
	import flash.display.Loader;

	public class OrderedLoaderSpike extends MovieClip {

		private var urlsArray:Array;

		public function OrderedLoaderSpike() {

			// provide your own images
			urlsArray = new Array();
			urlsArray.push("1.jpg");
			urlsArray.push("2.jpg");
			urlsArray.push("3.jpg");
			urlsArray.push("4.jpg");
			urlsArray.push("5.jpg");
			startLoading();
		}

		private function startLoading()
		{
			var numToLoad:Number = urlsArray.length;
			var numLoaded:Number = 0;
			var currentYOffset:Number = 0;
			var imgArray:Array = new Array();
			var imgIdx:Number = 0;

			for(var i=0; i < urlsArray.length; i++){
				var imageHolder:ImageHolder = new ImageHolder(imgIdx);
				imgArray.push(imageHolder);
				imgIdx++;

				var tempLdr = new Loader();
				var imgReq:URLRequest = new URLRequest(urlsArray[i]);
				tempLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete(imageHolder) );
				tempLdr.load(imgReq);
			}

			function onComplete(imageHolder:ImageHolder)
			{
				return function(e:Event)
				{
					var img:Loader = e.target.loader;
					imageHolder.setLoader(img);
					numLoaded++;

					if(numLoaded == numToLoad)
					{
						for(var i=0;i < imgArray.length; i++)
						{
							for(var j=0; j < imgArray.length;j++)
							{
								if(i == imgArray[j].getIdx())
								{
									addChild(imgArray[j].getLoader());
									imgArray[j].getLoader().y = currentYOffset;
									currentYOffset += imgArray[j].getLoader().height + 20;
								}
							}
						}
					}
				};
			}
		}
	}
}

package  {

	import flash.display.Loader;

	public class ImageHolder {

		private var idx:Number;
		private var loader:Loader;

		public function ImageHolder(theIdx:Number) {
			loader = null;
			idx = theIdx;
		}

		public function setLoader(v:Loader)
		{
			loader = v;
		}

		public function getLoader():Loader
		{
			return loader;
		}

		public function getIdx():Number
		{
			return idx;
		}

	}

}

Another (perhaps simpler) way is to not load the images in a loop at all, and instead have an array with the URL of the images to load. Then, you start to load the first image in a function, let’s call it loadExternalImage(). Once the load completes, you call loadExternalImage() again to load the next URL in the array, and so on, until you’ve traversed the entire array. Your choice really.

Zend_Form Check For Existing Email Address In Database

If you’re coding a registration form you will either want to check if a username or an email address is already present in the database. This is very easy to do, assuming you are familiar with using Zend_Form:

 $validator = new Zend_Validate_Db_NoRecordExists('user', 'email'); // user is the table name, and email is the column
        $validator->setMessage("Error: The e-mail has already been registered"); // set your own error message
        $this->addElement('text', 'email', array(
            'label' => 'E-mail Address',
            'required' => true,
            'filters' => array('StringTrim'),
            'validators' => array(
                'EmailAddress',
                $validator
            )
        ));

That’s all. NOTE: This might be obvious but you cannot chain the setMessage(…) function directly to the end of new Zend_Validate_Db_NoRecordExists(‘user’, ‘email’);

If you are unfamiliar Zend_Form, here’s a full example:


/* application/forms/Register.php */

class Default_Form_Register extends Zend_Form {

public function init($options = null) {
$this->setMethod('post');

$this->addElement('text', 'firstName', array(
'label' => 'First Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));

$this->addElement('text', 'lastName', array(
'label' => 'Last Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));

$validator = new Zend_Validate_Db_NoRecordExists('user', 'email');
$validator->setMessage("Error: The e-mail has already been registered");
$this->addElement('text', 'email', array(
'label' => 'E-mail Address',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
$validator
)
));

$password = $this->addElement('password', 'password', array(
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(8, 20)),
),
'required' => true,
'label' => 'Password',
'id' => 'password'
));

$register = $this->addElement('submit', 'register', array(
'required' => false,
'ignore' => true,
'label' => 'Register Now',
));

}

Make Meteorite Craters on Your Desk In Photoshop

In this tute we’re going to make meteorite craters on your desk! Here’s a preview of what you will come up with at the end:

 

 

Step 1. Go File->Open, and open up a picture of a desk:

Step 2. Go File-> Open, and open up a picture of a crater like the one below. Again I got it from Google by searching up “crater”. Drag it onto the image of the desk. A new layer should be created automatically when you drag it onto :

Step 3. While on the crater layer, make a selection like shown below. After you have made the selection, press Ctrl+Alt+D. A prompt will come up for feathering. Make the feather size 3px:

Step 4. Once you have done that, you probably won’t notice any change. Now drag the selection to the right and you should get this:

Now press Ctrl-D to deselect that selection.

Step 5. Use the eraser to erase the left over square on the left. We won’t be needing that anymore!

Step 6. Position the crater where you desire, then change the Layer Blending to Hard Light:

and you should get this result:



Step 7. The crater is a bit too large, so press Ctrl-T and size it down a little, to whatever you think is good.

Step 8. Now go to Blending Options of the crater layer and make these changes:

What it does is give the crater a bit of a burnt look on the outside:

Step 9. Hit Ctrl-J 3 times while having the crater layer selected. This will make copies of the crater. Resize and arrange them so you get something like this:

And that’s pretty much it!

I highly, highly recommend that you play around with the blending of the crater. We used Hard Light in this tutorial. But try others. I found that in addition to hard light, vivid light, linear light and linear burn all work pretty well. It depends on the effect you are looking for! You can also use small (maybe 3px) natural brushes with it set on color burn to create extra textures around the impact craters.

Also, take a picture of your own desk with books and computers and stationary, and you! That would look a whole lot more interesting.

Finally, some creative ideas:


This is OK, but to push the point of this fake advertisment for an imaginary website, there should probably be text books piled up on the table and someone sitting behind it.


If you’re a fan of Dune

I hope you found this tutorial useful and enjoyable!

 


Make A Simple Grundgy Minibanner In Photoshop

This is a very simple tutorial for beginners on how to make the grundgy effect around corners and edges. By the end of the tutorial, you will have this:

Step 1. Create a new document:

  • Width: 400px
  • Height: 100px
  • Background: Transparent or White. Either’s fine for our purposes.

Step 2. Make a new layer, call it “banner”:

Step 3. On the banner layer, make a rectangular selection and fill it black:

Step 4. Right click on the banner layer in the layers box and go to Blending Options. (You can also get to Blending Options from the top menu Layer -> Layer Style -> Blending Options).

Step 5. Make these changes in the blending options:


Step 6. If the marching ants selection is still selected, press Ctrl-D to deselect. You now have this:

Step 7. Now select the Eraser Tool (shortcut key E).

Step 8. With the Eraser Tool selected, configure these settings:

Step 9. With that done, use the Eraser Tool to dab sparingly around the corners and edges. Also hold down the mouse button and drag a little bit for some areas.

Tip: I highly suggest you try using other brushes to add some variation. The one to the left of the current brush is good.

Step 10. Add some text and there you have it. Piece of cake

This article was first published in 2007 on my old blog

Make a Sidescroller Game Scene In Photoshop

In this tutorial, we’re going to be making a scene that’s sort of like Super Mario. Except Super Mario won’t be in it.

By the end of the tutorial, you might have something like this:

Step 1. Open up a document of these dimensions:

Step 2. Make a new layer and call it “sky”:

Step 3. Use the Paint Bucket Tool to fill the layer black.
Step 4. Right click on the “sky” layer in the layers panel, and go to Blending Options:

Step 5. Make a new layer called “cloud”:

Step 6. Get the Elliptical Marquee Tool and draw a circle with it.

Step 7. Make sure Add to Selection is selected in the Elliptical Marquee settings tool bar:

Step 8. Now draw several more circles, each one overlapping another. Because you have Add to Selection selected, it will join all the circles together:

Step 9. Get the Paint Bucket Tool and fill the cloud black:

Step 10. Press Ctrl-D to deselect the marching ants:

Tip: If you feel that your cloud’s shape looks a bit weird, try following these 2 guidelines:

  • 1. Try to keep the general shape of your cloud a triangle. Keep the bottom of the cloud relatively flat.
  • 2. Use the SHIFT key while drawing ellipses to make them all circles, rather than elongated ovals.

Step 11. Go to the Blending Options for the cloud and give it these settings:

and these…

and you will get this:

Step 12. Go ahead and make another cloud of a different size. Make it a little different of course.

Note that when you create a new cloud and fill it in with black, you DO NOT HAVE TO go into the blending options and set everything up again! Instead, just copy the layer style from the original cloud onto the new cloud, as illustrated below:

and then…


Step 13. Having 2 clouds is enough for at this point, but if you want to make it look better, make some more clouds

Now we will make a rainbow that goes between the 2 goes.

Step 14. Create a new layer called “Rainbow”.

Step 15. Get the Rectangular Marquee Tool and draw a stripe like this, with the color indicated:

Step 16. Press Ctrl-D to deselect the marching ants, then duplicate the yellow stripe layer and use the Paint Bucket Tool to fill it in with #c0ff00. Then, move it downwards to reveal the yellow stripe:

Step 17. Do it a third time … you know the drill:

Step 18. Select all 3 stripe layers (Ctrl+ Click each of them), and click on merge layers. Now the raindbow is one layer.

Step 19. Go to Filter->Distort->Polar Coordinates:

Press OK, and you should have an upside down arch which is your rainbow.

A Tip: If you have Adobe Photoshop CS2 +, you can also do this step using the warp tool. To enter the warp tool, you need to press Ctrl-T to while having your rainbow selected. On the top toolbar settings for the transformation, there will be a button that when clicked, will allow you to enter the warp mode. Select a premade warp style.
Step 20. Arrange the graphics however you want to. You will need to use Ctrl-T to rotate the maybe resize the rainbow. Also you will need to, in the layers box, make the rainbow layer behind the clouds:

Now, let’s make some land.

Step 21. Download this striped graphic:

You can make your own stripes if you wish.
Step 22. Open up the striped graphic in Photoshop. Go to Edit->Define Pattern:

Step 23. Now you can close the striped file and go back to the file we were working on.

Step 24. Make a new layer and call it “land”.

Step 25. Select the Rounded Rectangle Tool and give it these settings:

  • Foreground color to black
  • Radius 15px

Step 26. Draw a solid black rectangle like this:


Step 27. For the rectangle, give it these settings:

Step 28. Make some more stuff! You should be able to do the following easily:

TIPS:

  • The pipe is just 2 rectangles stacked on top of each other, with the same blending options. The gradient for the pipe is:
  • The stars are made using the Brush Tool, with these settings:

Use different sizes and opacities for the stars.

That’s it Hope you learnt something in this tutorial. If you want to help me improve my tutorials, please leave a comment? Is this too easy? Is it hard to understand? Etc.

Thanks! Cya next time

Alien Organism Photoshop Tutorial

Ok! Let’s create an alien organism. Haven’t you always wanted to do that? No? Ok. Anyway this tutorial is rated easy and you should have the final product done in a few minutes.


This is what we will end up with

Alright let’s get started

Step 1. Make and new file, and give it these settings

Step 2. Make a new layer and fill it with a black. You should now have the original background layer, and the new layer filled with black.

TIP: Shortcut key to fill is Alt-Backspace.

Step 3. Select the Brush Tool, give it the following settings, and set the foreground color to white:
(click to enlarge)

Step 4. Using the brush tool, draw something like the following on the layer that you created in Step 2. No need to be too exact, but draw as smoothly as you can:

Step 5. Select the Smudge Tool smudge.jpg and give it these settings.
(click to enlarge)

Step 6. Using the smudge tool, smudge out these little “hairs”. Just click on the thick line you drew before and drag out.

Step 7. Now go Filter -> Distort -> Diffuse Glow, and give it these settings.

Step 8. Go to Image -> Adjustments -> Brightness/Contrast. Do this:

Step 9. Go to Image->Adjustments->Color Balance, and do the following:

Step 10. Finish!

This tutorial was first published in 2007 on my old blog.

photoshop_cs3_63x63

Make A Filmstrip In Photoshop

We’re going to make a filmstrip in Photoshop, which will look like this at the end:

Step 1. Open a new document with these settings:

  • 300 by 300 pixels
  • Transparent background

Note: Below you’ll notice I’ve made the background white. I made a little mistake. Make it transparent!

Step 2. Make a new layer:

Step 3 a. Make a rectangle at this position by using the Rectangular Marquee Tool and holding down SHIFT as you drag out:

Step 3 b. Now fill in the rectangle with BLACK using the Paint Bucket Tool.

Step 4. While having the layer selected, press Ctrl-J to duplicate it:

Step 5a. Press Ctrl-T while having the “base copy” layer selected. At the top of the window you’ll find a bar like below. Make the changes:

Step 5b. You won’t see much until you fill the “base copy” layer in with the color #1c1b1b. So fill it in and this is what you should get:

<— the inner rectangle is “base copy” (#1c1b1b)

Step 6. Create a new layer, named “holes”.

Step 7. On that newly created layer, use the Rectangular Marquee Tool to draw a rectangle like this:

Step 8. Fill in that rectangle with white.

Step 9. Press Ctrl-D to deselect the marching ants.

Step 10. While still on the “holes” layer, hit Ctrl-J a mighty 6 times to duplicate it 6 times. Now you will have 7 of the rectangles stacked on each other:

Step 11. Now select the original “holes” layer and drag it to the position as shown below. Then go to the “holes copy 6″ layer and drag to the position as shown. Use arrow keys for accurate positioning:

Step 12. Select all layers by Ctrl + left mouse clicking all layers:

Step 13. Make sure  is selected!

Step 14. Making sure you did steps 12 and 13, click on Distribute left edges, which should be a button near the top of the Photoshop window. It’s shown here:


Step 15. With all the hole layers still selected, hit Ctrl-G to group them and name the group “holes”.

Step 16. Duplicate the group:

—>

Step 17. Move the duplicated group down to the bottom:
<– drag the duplicated group down here

Step 18. Select EVERYTHING in the layers panel (except the background) and group them yet again (Ctrl-G). Name it “filmstrip”.

Step 19. Duplicate the filmstrip group 5 times and drag them into position so you get the following:

Step 20. Create a new layer and call it “gloss”.

Step 21. Make this selection:

Step 22. Fill the selection with BLACK.

Step 23. Right click on the gloss layer (in the layers panel), and go to Blending Options. Give it these settings:
–>–>

Step 24. Now, group EVERYTHING (except the background), into 1 layer and call it “ALL”.

At this point, it’s a good idea to SAVE AS your file under a different name.

Step 25. Right click on the layer (in the layers panel) and Convert to Smart Object. We need to do this, because we can’t otherwise peform a filter on a group. If you DON’T have the Convert to Smart Object button because you are using a version of Photoshop older than Photoshop CS2, that’s ok. Instead, you need to merge everything into one layer – then you can proceed.

Step 26. Now go Filter-> Distort -> Wave and do the following. Actually I just clicked “Randomize” a few times:

And you’re done:


FINAL NOTE:

If you’re going to use this graphic over a website/banner that does not have a white background, the white holes won’t show through. This a simple thing to fix.

Step 1. Merge everything into a single layer (apart from the background)

Step 2. Using the Magic Wand Tool, select and delete the holes (making sure the anti-alias checkbox is off)

Remember: Every time you do any sort of destructive editing such as a merge, always save the old file first and save the new one with a different name!

That’s it for today! Hope you enjoyed this tutorial.

This tutorial was first published in 2007 on my old blog.

jQuery AJAX + Zend Framework Requesting And Receiving Data

The title is a mouthful, but all we want to do is to make an AJAX call to the server, and get some data back, using jQuery – plain old jQuery, not Zend’s plugin – and working within the Zend Framework’s MVC model. In the previous post I wrote on how to make an AJAX call to the server, but never said how to get some data back! So this is what we’re going to do now. This is based on the previous article so you might want to read that if you haven’t yet. But if you know a bit of jQuery and Zend Framework then you might want to just jump straight in. In any case you need to understand OOP and how MVC works.

In the view, you will have this Javascript code:

var myData = "name=William Adama&alias=Husker&job=Commander of the Colonial Fleet";
$.ajax({
            type: "POST",
            url: "http://www.example.com/yourcontroller/process/format/html",
            data: myData,
            success: function(data) {
                alert("AJAX call successful and this data was returned: " + data);
            },
            error: function() {
                  alert("AJAX call an epic failure");
            }
        });
        return false;

Here we made some changes from the previous article. First we need to add format/html to the end of the URL, like this:

 url: http://www.example.com/yourcontroller/process/format/html

We need this extra bit to tell Zend Framework that we are expecting an HTML response. If you omit this, like I did in the first place, then your layout will be returned, and nothing else. More on this in a second. Also note that we added the data parameter to the success callback function. This variable will hold the data that comes back from the server – you can name it anything you want of course.

Next, we look at your controller class. You will need to have an init function in your controller, which will be called automatically when an action in your controller is called. This is what it looks likes:

public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
 $ajaxContext->addActionContext('process', 'html')
                  ->initContext();
}

This basically tells the controller that for the process action, you want to enable AJAX, and that you wish to return HTML data. Now we get to the process action controller:

public function processAction()
{
    // do whatever you need to do here
    // DO NOT fall for the mistake of setting the action to not render the layout. You do not need to do this.
}

There was nothing to that, really. Just write any code you need to write in that action. For an example, view the previous article. Then, create a view called process.ajax.phtml, instead of the usual process.phtml as this is where the Zend Framework will look for your view. Of course, place the view in the same folder as you would place any other view for the controller. And, like any other view you can set data for the view, with $this->view->yourvariable = yourdata, but you know that already :-)

Finally, our AJAX view (process.ajax.phtml):

echo "This is the data I'm returning"; // just echo it out!

And that’s all there is to it! There are other ways to achieve jQuery and Zend Framework integration, but this is my preferred method. It’s really simple.

jQuery AJAX + Zend Framework Very Simple Example

I’m assuming you’re using the built in MVC framework that the Zend Framework offers. Also, I do not use ZendX_JQuery, just plain old jQuery. Right now I’m much more comfortable working directly with jQuery rather than going through yet another level of abstraction.

In the view, you will have this Javascript code:

var myData = "name=William Adama&alias=Husker&job=Commander of the Colonial Fleet";
$.ajax({
            type: "POST",
            url: "http://www.example.com/yourcontroller/process",
            data: myData,
            success: function() {
                alert("AJAX call a success!");
            },
            error: function() {
                  alert("AJAX call an epic failure");
            }
        });
        return false;

You need to put that code in a function and call it from somewhere, of course. Note that myData is a URL query string, and you may have noticed that there are spaces in the URL which you cannot have, but the spaces are automatically encoded into + signs and gets automatically decoded later in PHP so it’s okay. Finally, replace “yourcontroller” with the name of your controller, and “process” is the name of the controller action I chose, choose any you want.

You will retrieve your post data in your controller action:

public function processAction() {
$myData = $this->getRequest()->getParams(); // $myData is a PHP array
    
// This will turn the array back into the original URL query string
$decodedData = http_build_query($myData); 

// Get the name (William Adama)
$name = $this->getRequest()->getParam('name');

 
// Now you know how to get any data you want and to do whatever you want with the data
}

Just one more thing – $myData will include controller, action and module data that you probably don’t want. If you need to remove them from the array for any reason it is easy:

public function processAction() {
$myData = $this->getRequest()->getParams(); // $myData is a PHP array
unset($myData ['controller']);
unset($myData ['action']);
unset($myData ['module']);

// This will turn the array back into the original URL query string
$decodedData = http_build_query($myData);

// Get the name (William Adama)
$name = $this->getRequest()->getParam('name');


// Now you know how to get any data you want and to do whatever you want with the data

}

Need to get data back from the AJAX call? No problem – view the next article.

Logging and Debugging In The Zend Framework

It’s not possible to develop an application without having first set up logging, otherwise we won’t be able to debug our application. Don’t use echo and print_r for logging because you’ll soon find out its inefficient to do things like that, and that your outputs will disappear into the abyss when you try doing it in controllers because the view for the controller action will be rendered instead of your logging info. Just set it up, it’ll take all but 5 mins.

The most effective method I find for logging in the Zend Framework is to use Firefox+Firebug+FirePHP. If you don’t have any of those, then install them now. You might also be able to use Google Chrome but I personally don’t like to use that browser for development, plus I don’t even know if Firebug with FirePHP works properly on it at this time.

Assuming you’re doing things the latest way, you will have a Bootstrap.php containing a bootstrap class extending Zend_Application_Bootstrap_Bootstrap. With no sarcasm, I LOVE Zend Framework’s naming convention – it’s just so damn logical. Anyway all this is in the quickstart tutorial on the Zend Framework website. In that file just create a new resource under any method name, just make sure you have the underscore in front of the method name so that the Zend Framework “automagically” executes it:

// A method in the Bootstrap class
protected function _startLogging()
{
$this->bootstrap('frontController'); // as you need the frontController for debugging we need to guarantee its availability
$logger = new Zend_Log();
$this->_logger = $logger;
Zend_Registry::set('myLogger', $logger);
}

Then, anywhere in application you can now have access to the logger by doing this:

$myLogger = Zend_Registry::get('myLogger');
$myLogger->log("Anything you want to output", Zend_Log::DEBUG);

In order to see your output, turn on Firebug in the bottom right hand corner of the browser, and click on the Console tab.

By the way, this might seem obvious but it caught me during debugging – don’t concatenate strings to Arrays, you won’t get your array output since it will be converted into a String automatically, its just how loosely typed languages work:

$myArray = array("foo", "bar", "bleh");
$myLogger = Zend_Registry::get('myLogger');
$myLogger->log("Array output: " . $myArray, Zend_Log::DEBUG); // nooooo

Okay. Now you can get on with debugging, which arguably is the main job of a programmer :P