Separating Complex Objects from Background


Separating Complex Objects from Background

You can find a lot of tutorials how to separate complex objects from the background. But I would like to invite your attention to another one unique simple tutorial how to achieve the desired effect in just a few steps. I got this method by experimenting.

In the beginning you should find some appropriate picture to work with. You can use Google Images or also feel free to use mine picture. Open up the picture and start with tutorial.

Separating Complex Objects from Background 01

Apply Filter > Extract with similar settings to these:

Separating Complex Objects from Background 02

This is where we start to extract the image first of all zoom into the image with Zoom Tool so you can clearly see the outline and set the brush size to a suitable size and then simply draw around the outline of the woman’s hairstyle with Edge Highlighter Tool. If you made wrong line, you can remove it with Eraser Tool. Now fill in the area which you want extracting to do this select the Fill Tool on the left hand toolbar and simply click inside of the drawn outline.

Separating Complex Objects from Background 03

Now press OK in the top right of the window and you should go back to the normal Photoshop window, and if you did the last steps correctly you will have an image without a background, if all done correct the edges will look fine, if not then you may find some discrepancies which can simply be erased.

Separating Complex Objects from Background 04

After that create a new layer under and fill it with color of #aed2da.

Separating Complex Objects from Background 05

Now we can see that we have some defects on woman’s hair. It is not a big problem, just get out the Eraser Tool and select one of standard brushes from Photoshop palette:

Separating Complex Objects from Background 06

Reduce brush size to 25 pixels and process areas where you can see visible defects.

Separating Complex Objects from Background 07

Now, move to the next step. After processing problem areas with Eraser Tool we may have not so clear image parts, for example like we have from the left and right parts. For removing this problem select the Smudge Tool (Brush: 2 px, Mode: Darken, Stregth: 95%) and add a few strokes as shown on the picture below:

Separating Complex Objects from Background 08

Then increase the sharpness for these areas with Sharpen Tool (Brush: 60 px, Mode: Normal, Stregth: 30%).

Separating Complex Objects from Background 09

We are done on this step. Isolated picture looks nice and all parts of hear looks realistic. If you don’t have the same good results, just try to experiment to get the best results!

Separating Complex Objects from Background 10


Add Your Face to Movie Poster

Add Your Face to Movie Poster

You can find a lot of tutorials how to paste another face to the picture. Here I’m planning to show you my own way how to do this step by step and explain how to process every small detail in this design. You will look as a real real star!

Let’s start by finding the poster where you wanna be main actress or actor. For example, I will use Twilight movie poster (download here) or also feel free to use another posters from another movies what you like. Ok, then I need to put our picture on it. As for me, I just decided to use a picture of serious young lady (download here). Open up your photo and use Polygonal Lasso Tool to select face on the picture.

Add Your Face to Movie Poster

Press Ctrl+C to copy selected area, then open up canvas with movie poster and paste (Press Ctrl+D) there copied part of image from you picture. If you need to rotate your face to find suitable position and size for it, just use Ctrl+T for free transform.

Add Your Face to Movie Poster

After that we can move to next step. For now use the Eraser Tool and a soft round brush about 50 px to remove hard edges from face fragment layer.

Add Your Face to Movie Poster

As we can see, skin color of face fragment is bit different from original color face on the movie poster. How we can resolve this problem? Very easy! Just apply Image > Adjustments > Color Balance with similar presets to these:

Add Your Face to Movie Poster

Now the result looks better as before. We got much correct saturation for face skin.

Add Your Face to Movie Poster

Ok, now use Dodge Tool (Brush: 30px, Range: Midtones, Exposure: 30%) to make some parts of face a little bit lighter.

Add Your Face to Movie Poster

See the difference now:

Add Your Face to Movie Poster

After that we have to make some burn work with the opposite side of the face. Select the Burn Tool (Brush: 25px, Range: Midtones, Exposure: 40%) and process eyes area with it.

Add Your Face to Movie Poster

Move to the next step. Now we need to add global shadow to the left part of face. Create new layer, after that use the Polygonal Lasso Tool to create selection and fill it with color of #1d0d08 on the new layer.

Add Your Face to Movie Poster

Remove selection with Ctrl+D and Apply Filter > Blur > Gaussian Blur to blur current layer content about 3,8 pixels and change layer mode to Multiply.

Add Your Face to Movie Poster

Now will be the hardest part of doing this tutorial. We need to clear shadow layer with Eraser Tool and soft round brush with different sizes to get realistic view of shadow presence. I think, for the beginners in Photoshop it will be a little bit harder to get realistic result, but you have to try anyway. I got something like this:

Add Your Face to Movie Poster

We are finished with our tutorial! Now you’re looking like a great actress on that movie poster!

Add Your Face to Movie Poster


Designing Gear Wheel in Photoshop

Are you hungry for new tutorials how to create objects in Photoshop? Ok, I have one interesting tutorial for you.

Ok, let’s start! Create a new document sized 500×500 pixels. Drag a linear gradient with colors of #eaf8fb and #d0dee1 as shown on a picture below. It will be background for putting gear wheel on it.

After that start with creating gear wheel. Select Shape Tool and choose on of standard Photoshop shapes

Designing Gear Wheel in Photoshop

Designing Gear Wheel in Photoshop

and draw out it in the middle of our canvas with white color.

Designing Gear Wheel in Photoshop

Then reduce height about 60% for this shape and rasterize it with Layer > Rasterize > Shape:

Designing Gear Wheel in Photoshop

Load selection of shape with Select > Load Selection and fill it with grey to transparent gradient on the same layer (use color of #6d848c).

Designing Gear Wheel in Photoshop

Remove selection with Ctrl+D. Now, we should add lower base and process lateral surface texture. Duplicate current layer with Ctrl+J and move lower layer 20 pixels down.

Designing Gear Wheel in Photoshop

Then use the Polygonal Lasso Tool to connect the top edges and bottom edges of the gears with selection and fill it with whatever color you want.

Designing Gear Wheel in Photoshop

After that deselect chosen area with Ctrl+D and apply Color Overlay (link to 08) layer style for current layer.

Designing Gear Wheel in Photoshop

Designing Gear Wheel in Photoshop

Then create layer under and merge it with previous to get all effects in one layer. Ok, now we need to add glares and shadows to lateral surface to show metallic sheen effect on it. Use Polygonal Lasso Tool again and select some area between two nearest lugs of gear wheel.

Designing Gear Wheel in Photoshop

Then use Burn Tool (Brush: 15 px, Range: Shadows, Exposure: 50%) to add shadow in between two lags.

Designing Gear Wheel in Photoshop

After that reduce brush size to 5 pixels and add dark shadow line in deepest part to increase metal texture reflection.

Designing Gear Wheel in Photoshop

Change Burn Tool to Dodge Tool (Brush: 15 px, Range: Midtones, Exposure: 70%) and add a few glares from the left and right sides:

Designing Gear Wheel in Photoshop

Remove selection with Ctrl+D. Add the same affect to each visible area between each lug.

Designing Gear Wheel in Photoshop

Ok, we are done with lateral area surface. Move to the next step. Go to the upper part of gear wheel and bring some glare there also. For this effect use the Polygonal Lasso Tool again, create the same selection which you can see on the picture below and feel it with white color on the new layer.

Designing Gear Wheel in Photoshop

Remove selection with Ctrl+D and apply Filter > Blur > Radial Blur with similar settings to these:

Designing Gear Wheel in Photoshop

Your result should be the same as mine:

Designing Gear Wheel in Photoshop

Then apply Filter > Blur > Gaussian Blur with next presets:

Designing Gear Wheel in Photoshop

We received picture like so:

Designing Gear Wheel in Photoshop

Now, press Ctrl and click the upper part layer thumbnail in the layers palette to create selection and use Ctrl+Shift+I to invert it, then press Delete button to clear selection.

Designing Gear Wheel in Photoshop

Remove selection with Ctrl+D and after that merge all layers in one except background layer. Move to the next step. We need to create a hole inside the gear wheel. Get out the Elliptical Marque Tool and create selection similar to mine and fill it wit color of #6d848c.

Designing Gear Wheel in Photoshop

Select Burn Tool again to make some small dodge work.

Designing Gear Wheel in Photoshop

Deselect chosen area with Select > Deselect. Ok, now time to add the verge of gear wheel. For this effect use the Line Tool (Weight: 1px) and add white lines on each verge of gear wheel.

Designing Gear Wheel in Photoshop

Merge all layers with white lines in one, then use the Eraser Tool (Opacity: 50%) and a soft round brush about 70 pixels and make little clean work.

Designing Gear Wheel in Photoshop

Move to the last one step. To finish off our tutorial we gave to add some shadow under the gear wheel. Merge all layers except background layer in one and apply Drop Shadow (link to 25) layer style for new received layer:

Designing Gear Wheel in Photoshop

Designing Gear Wheel in Photoshop

Now we need to extract shadow effect to separate layer. Use Layer > Layer Style > Create Layer for this option. Move to new layer with shadow under the current layer and apply Filter > Blur > Motion Blur for it.

Designing Gear Wheel in Photoshop

Now, we have something like this:

Designing Gear Wheel in Photoshop

After that select Smudge Tool (Brush: 70 pixels) to increase the drop shadow on the sides just a little bit.

Designing Gear Wheel in Photoshop

We are done with this tutorial. Now we have realistic view gear wheel created by ourselves.

Designing Gear Wheel in Photoshop


Evening Eye Make Up Effect in Photoshop

makeup-24

Today I will show you how to imitate evening eye make up in Photoshop CS3. This lesson will be very useful to those who process the photos for fashion magazines.

So, let’s start by finding some appropriate picture of girl’s face. You can also use your own photos to experiment with, if you’re girl of course :) Go to Google Images and find needed photo or feel free to use mine also. Open up the photo and start to work with it.

makeup-01

I think it will be better to start with adding eye shadows to eyelids. Get out the Polygonal Lasso Tool and create selection similar to mine on the picture below:

makeup-02

Then holding Shift button and when the plus sign near cursor will appear just add second eye area selection. After that fill selected area with color of # 806475 on the new layer.

makeup-03

Remove selection with Ctrl+D and apply Filter > Blur > Gaussian Blur with next presets:

makeup-04

Change layer mode to Overlay:

makeup-05

To correct eye shadows borders we can apply Smudge Tool (Brush: 50 px, Mode: Normal : Strenght: 70%).

makeup-06

Then create a new layer and start with creating eyeliner effect. Use the Polygonal Lasso Tool again and create one more selection as on my picture below, then fill it with color of #282a37 on the new layer.

makeup-07

Deselect chosen area with Select > Deselect and apply Filter > Blur > Gaussian Blur with similar settings to these:

makeup-08

The result should be next:

makeup-09

After that apply Smudge Tool for this layer again.

makeup-10

Time to add white shining under the eyebrows. Create new layer, then select the Brush Tool and a soft round brush about 35px to color some area under eyebrows with white color.

makeup-11

After that apply Filter > Noise > Add Noise with similar settings to these:

makeup-12

Then change layer mode to Soft Light:

makeup-13

After that apply Blur Tool a little bit.

makeup-14

Ok, now make some clean work with Eraser Tool to bring shining realistic view.

makeup-15

Tome to color eyebrows. Create new layer, then select the Polygonal Lasso Tool again and create selected areas similar to mine and fill it with black color.

makeup-16

Remove selection with Ctrl+D and apply Filter > Blur > Gaussian Blur to blur current layer content about 1,5px, then reduce opacity to 40% for this layer.

makeup-17

And the last one thing that I would like to add is eyelashes. I’m gonna show you one interesting method how we can add it by using Pen Tool. Before we start making it, just get out the Brush Tool before and set up with the following settings for it:

makeup-18

Then set foreground color as black. After that select the Pen Tool (you need to make sure that you’re working with Paths instead of Shape Layers). Draw out the line using paths:

makeup-19

Then right-click and select Stroke Path.

makeup-20

A little dialog box will appear as in the screenshot. Choose Brush and make sure there is a tick next to Simulate Pressure. This is important as it will give your curve tapered ends which will make it rock!

makeup-21

You should get result similar to mine:

makeup-22

Next right click again and select Delete Path. Create more eyelashes on the same way.

makeup-23

Looks cool, isn’t it? Hope, you got the same good results as me, if not, just keep on training and you will good the best results! Good luck!

makeup-24


Creating a Javascript Bookmarklet

For nearly all problems there are probably a hundred different solutions. Recently one solution I have chosen for a few problems has been a Javascript bookmarklet. A bookmarklet is a regular bookmark that runs a bit of Javascript code instead of just going to a link. They are really useful for doing a small task on a website or webpage that you don’t have direct access to the backend or source of. So, today I am going to show you how to make a simple bookmarklet.

The bookmarklet today is going to grab a super high-res photo of Amazon Products. Ok, let me explain a little bit more. So, a designer co-worker uses super high-res product images for design mockups. Well, he typically would go scouring the internet for these images. However, he noticed that on Amazon product pages you can look at really large images of products using their Zoom viewer, but you could right-click and download the image from there. So I created a simple bookmarklet to grab the product id from the page url and then open up a link to the large image.

Okay, back to work. So a typical link which can be turned into a book looks like:

SOTC Tutorials

And the code looks like.

<a href="/tutorials">SOTC Tutorials</a>

So if we were going to do something javascript we could do something like:

And the code would be:

<a href="javascript:location.href=’http://switchonthecode.com/tutorials’">SOTC Tutorials</a>

Now, that just covers the basics of the syntax we are going to use for this. You can see above that to tell the browser to run our href as Javascript we need to start with javascript:. Ok so let’s jump to something a bit more complicated. The next piece of Javascript is going create an alert with the current time – I know we all love alerts.

<a href="javascript:(function(){ct=new Date();t=ct.getHours()+’:’+ct.getMinutes();alert(t);})();">Current Time</a>

Looking at the code we start by creating anonymous function and inside the function we create a new Date object, then use it to create a string of hours and minutes, and then show this (current time) in an alert.

So, now if you want to make this a Bookmarklet simply do one of two things.

  1. Drag the link to your bookmark toolbar.
  2. Create a bookmark. Copy the location of the link above and change location of the new bookmark you just created.

The final piece of code we are going to look a is the actual bookmarklet Javascript for the Amazon Image grabber.

regexp=new RegExp(‘/dp/[^/]+(?=/)’);
prod=location.href.match(regexp);
imgloc=‘http://ec2.images-amazon.com/images/P/’+prod[0].substring(4)+‘.01._SCRM_.jpg’;
location.href=imgloc;

The code starts with creating a regular expression that pulls the product id from a url. Next we run the expression on the current page url – it won’t work on this page – using the match to run the expression. Then the url for the large image is created. The last thing is to change the url of the page to go to the large image. Really, that is about it. For a link we wrap it with the aforementioned function and the javascript: starting. In link format this looks like:

<a href="javascript:(function(){regexp=new RegExp(‘/dp/[^/]+(?=/)’);prod=location.href.match(regexp);imgloc=’http://ec2.images-amazon.com/images/P/’+prod[0].substring(4)+’.01._SCRM_.jpg’;location.href=imgloc;})();">Amazon XL Image</a>

And the link:

Well, I hope you learned something today about Javascript links and Bookmarklets. If you have any questions or comments feel free to leave a comment below or head on over to the forums.

Creating a Javascript Bookmarklet

For nearly all problems there are probably a hundred different solutions. Recently one solution I have chosen for a few problems has been a Javascript bookmarklet. A bookmarklet is a regular bookmark that runs a bit of Javascript code instead of just going to a link. They are really useful for doing a small task on a website or webpage that you don’t have direct access to the backend or source of. So, today I am going to show you how to make a simple bookmarklet.

The bookmarklet today is going to grab a super high-res photo of Amazon Products. Ok, let me explain a little bit more. So, a designer co-worker uses super high-res product images for design mockups. Well, he typically would go scouring the internet for these images. However, he noticed that on Amazon product pages you can look at really large images of products using their Zoom viewer, but you could right-click and download the image from there. So I created a simple bookmarklet to grab the product id from the page url and then open up a link to the large image.

Okay, back to work. So a typical link which can be turned into a book looks like:

SOTC Tutorials

And the code looks like.

<a href="/tutorials">SOTC Tutorials</a>

So if we were going to do something javascript we could do something like:

And the code would be:

<a href="javascript:location.href=’http://switchonthecode.com/tutorials’">SOTC Tutorials</a>

Now, that just covers the basics of the syntax we are going to use for this. You can see above that to tell the browser to run our href as Javascript we need to start with javascript:. Ok so let’s jump to something a bit more complicated. The next piece of Javascript is going create an alert with the current time – I know we all love alerts.

<a href="javascript:(function(){ct=new Date();t=ct.getHours()+’:’+ct.getMinutes();alert(t);})();">Current Time</a>

Looking at the code we start by creating anonymous function and inside the function we create a new Date object, then use it to create a string of hours and minutes, and then show this (current time) in an alert.

So, now if you want to make this a Bookmarklet simply do one of two things.

  1. Drag the link to your bookmark toolbar.
  2. Create a bookmark. Copy the location of the link above and change location of the new bookmark you just created.

The final piece of code we are going to look a is the actual bookmarklet Javascript for the Amazon Image grabber.

regexp=new RegExp(‘/dp/[^/]+(?=/)’);
prod=location.href.match(regexp);
imgloc=‘http://ec2.images-amazon.com/images/P/’+prod[0].substring(4)+‘.01._SCRM_.jpg’;
location.href=imgloc;

The code starts with creating a regular expression that pulls the product id from a url. Next we run the expression on the current page url – it won’t work on this page – using the match to run the expression. Then the url for the large image is created. The last thing is to change the url of the page to go to the large image. Really, that is about it. For a link we wrap it with the aforementioned function and the javascript: starting. In link format this looks like:

<a href="javascript:(function(){regexp=new RegExp(‘/dp/[^/]+(?=/)’);prod=location.href.match(regexp);imgloc=’http://ec2.images-amazon.com/images/P/’+prod[0].substring(4)+’.01._SCRM_.jpg’;location.href=imgloc;})();">Amazon XL Image</a>

And the link:

Well, I hope you learned something today about Javascript links and Bookmarklets. If you have any questions or comments feel free to leave a comment below or head on over to the forums.

How to Build a Simple Twitter Client using Python

Building a Twitter client is nothing new to Switch On The Code. We’ve done it in WCF and Silverlight. To be honest though, using the Twitter API is a great way to exercise two very useful parts of a language and framework – making web requests and parsing XML. That’s what we’re going to do today. We’re going to build a very simple command line twitter client (read-only) using Python.

Today’s app will be very simple. It will request Switch On The Code’s Twitter feed and display them with their dates. Here’s what the first five tweets in the output will look like:

Date: Thu Jul 22 19:46:19 +0000 2010
Tweet: VS 2010 Productivity Power Tools Update (with some cool new features) http://sotc.me/46680 via @scottgu #vs2010 #programming

Date: Thu Jul 22 17:34:45 +0000 2010
Tweet: SQLite 3.7.0 released http://sotc.me/92864 #sqlite

Date: Wed Jul 21 19:08:01 +0000 2010
Tweet: 20+ Required #Windows Apps: Web DesignerGÇÖs Choice http://sotc.me/28662 via @nettuts – I personally love Notepad++ myself!

Date: Mon Jul 19 20:20:23 +0000 2010
Tweet: Windows Phone 7 in-depth preview http://sotc.me/58189 via @engadget #wp7 #microsoft

Date: Mon Jul 19 17:13:38 +0000 2010
Tweet: Would love to get a hold of Windows Phone 7 device to build a couple applications for it, anyone know how to go about that? #windowsphone7

Python has a very large and powerful framework behind it, do doing simple things like making web requests and parsing XML are fairly straight forward and don’t require a lot of code. Let’s start by requesting the XML from Twitter’s API.

import httplib

# Open a connection to twitter.com.
twitterConn = httplib.HTTPConnection("www.twitter.com")

# Requestion Switch On The Code’s tweets.
twitterConn.request("GET", "/statuses/user_timeline.xml?screen_name=SwitchOnTheCode")
twitterResponse = twitterConn.getresponse()

# Check that everything went ok.
if twitterResponse.status != 200:
  print("Failed to request tweets.")
 
# Read the response.
tweets = twitterResponse.read()

# Close the connection.
twitterConn.close()

The first thing we do is create an HTTPConnection object for twitter.com. We then tell it to request the timeline for the user SwitchOnTheCode. Next, we get the response as an HTTPResponse object. I do a quick check to make sure the request went ok, since we all know how often Twitter goes down. All that’s left to do is simply read the contents of the response, which will be our XML.

Now we need to parse the XML. There are a couple of available options, but I chose the DOM approach as I think it makes more logical sense.

import httplib
from xml.dom.minidom import parseString

# Open a connection to twitter.com.
twitterConn = httplib.HTTPConnection("www.twitter.com")

# Requestion Switch On The Code’s tweets.
twitterConn.request("GET", "/statuses/user_timeline.xml?screen_name=SwitchOnTheCode")
twitterResponse = twitterConn.getresponse()

# Check that everything went ok.
if twitterResponse.status != 200:
  print("Failed to request tweets.")
 
# Read the response.
tweets = twitterResponse.read()

# Close the connection.
twitterConn.close()

#Parse the XML.
twitterDom = parseString(tweets)

# Find all the status tweets.
for tweet in twitterDom.getElementsByTagName("status"):
  for tweetParts in tweet.childNodes:
    # Find the date tag.
    if tweetParts.nodeName == "created_at":
      for textNode in tweetParts.childNodes:
        # Find the contents of the date tag.
        if textNode.nodeType == textNode.TEXT_NODE:
          print("Date: " + textNode.nodeValue)
    # Find the tweet tag.
    elif tweetParts.nodeName == "text":
      for textNode in tweetParts.childNodes:
      # Find the contents of the tweet tag.
        if textNode.nodeType == textNode.TEXT_NODE:
          print("Tweet: " + textNode.nodeValue.encode(‘utf-8’) + "\n")

Using Python’s minidom, we first parse the XML returned from Twitter using parseString (don’t forget to import parseString at the top of the file). Now things get a litte tricky. We need to rip through the DOM looking for the items we want to display. First off, every tweet is stored beneath a “status” tag, so we need to loop through every one of those. Underneath each status tag there’s the date (created_at) and the actual tweet (text), so we need to loop through every child of the status tag looking for those. Once we find one, we then need to find the text contained within it. Text is contained in TEXT_NODE type nodes, so we need to search through the children of our created_at and text tags looking for that specific type. Once we find it, we then print the nodeValue and we’re done.

Since tweets are Unicode, I needed to encode the text as utf-8 before printing it to the console.

And that’s it. With just a few lines of code, and some pretty complicated DOM traversing, we’ve got a very basic Twitter reader built in Python. If you’ve got any questions or comments, feel free to leave them below or head on over to our forums.

How to Build a Simple Twitter Client using Python

Building a Twitter client is nothing new to Switch On The Code. We’ve done it in WCF and Silverlight. To be honest though, using the Twitter API is a great way to exercise two very useful parts of a language and framework – making web requests and parsing XML. That’s what we’re going to do today. We’re going to build a very simple command line twitter client (read-only) using Python.

Today’s app will be very simple. It will request Switch On The Code’s Twitter feed and display them with their dates. Here’s what the first five tweets in the output will look like:

Date: Thu Jul 22 19:46:19 +0000 2010
Tweet: VS 2010 Productivity Power Tools Update (with some cool new features) http://sotc.me/46680 via @scottgu #vs2010 #programming

Date: Thu Jul 22 17:34:45 +0000 2010
Tweet: SQLite 3.7.0 released http://sotc.me/92864 #sqlite

Date: Wed Jul 21 19:08:01 +0000 2010
Tweet: 20+ Required #Windows Apps: Web DesignerGÇÖs Choice http://sotc.me/28662 via @nettuts – I personally love Notepad++ myself!

Date: Mon Jul 19 20:20:23 +0000 2010
Tweet: Windows Phone 7 in-depth preview http://sotc.me/58189 via @engadget #wp7 #microsoft

Date: Mon Jul 19 17:13:38 +0000 2010
Tweet: Would love to get a hold of Windows Phone 7 device to build a couple applications for it, anyone know how to go about that? #windowsphone7

Python has a very large and powerful framework behind it, do doing simple things like making web requests and parsing XML are fairly straight forward and don’t require a lot of code. Let’s start by requesting the XML from Twitter’s API.

import httplib

# Open a connection to twitter.com.
twitterConn = httplib.HTTPConnection("www.twitter.com")

# Requestion Switch On The Code’s tweets.
twitterConn.request("GET", "/statuses/user_timeline.xml?screen_name=SwitchOnTheCode")
twitterResponse = twitterConn.getresponse()

# Check that everything went ok.
if twitterResponse.status != 200:
  print("Failed to request tweets.")
 
# Read the response.
tweets = twitterResponse.read()

# Close the connection.
twitterConn.close()

The first thing we do is create an HTTPConnection object for twitter.com. We then tell it to request the timeline for the user SwitchOnTheCode. Next, we get the response as an HTTPResponse object. I do a quick check to make sure the request went ok, since we all know how often Twitter goes down. All that’s left to do is simply read the contents of the response, which will be our XML.

Now we need to parse the XML. There are a couple of available options, but I chose the DOM approach as I think it makes more logical sense.

import httplib
from xml.dom.minidom import parseString

# Open a connection to twitter.com.
twitterConn = httplib.HTTPConnection("www.twitter.com")

# Requestion Switch On The Code’s tweets.
twitterConn.request("GET", "/statuses/user_timeline.xml?screen_name=SwitchOnTheCode")
twitterResponse = twitterConn.getresponse()

# Check that everything went ok.
if twitterResponse.status != 200:
  print("Failed to request tweets.")
 
# Read the response.
tweets = twitterResponse.read()

# Close the connection.
twitterConn.close()

#Parse the XML.
twitterDom = parseString(tweets)

# Find all the status tweets.
for tweet in twitterDom.getElementsByTagName("status"):
  for tweetParts in tweet.childNodes:
    # Find the date tag.
    if tweetParts.nodeName == "created_at":
      for textNode in tweetParts.childNodes:
        # Find the contents of the date tag.
        if textNode.nodeType == textNode.TEXT_NODE:
          print("Date: " + textNode.nodeValue)
    # Find the tweet tag.
    elif tweetParts.nodeName == "text":
      for textNode in tweetParts.childNodes:
      # Find the contents of the tweet tag.
        if textNode.nodeType == textNode.TEXT_NODE:
          print("Tweet: " + textNode.nodeValue.encode(‘utf-8’) + "\n")

Using Python’s minidom, we first parse the XML returned from Twitter using parseString (don’t forget to import parseString at the top of the file). Now things get a litte tricky. We need to rip through the DOM looking for the items we want to display. First off, every tweet is stored beneath a “status” tag, so we need to loop through every one of those. Underneath each status tag there’s the date (created_at) and the actual tweet (text), so we need to loop through every child of the status tag looking for those. Once we find one, we then need to find the text contained within it. Text is contained in TEXT_NODE type nodes, so we need to search through the children of our created_at and text tags looking for that specific type. Once we find it, we then print the nodeValue and we’re done.

Since tweets are Unicode, I needed to encode the text as utf-8 before printing it to the console.

And that’s it. With just a few lines of code, and some pretty complicated DOM traversing, we’ve got a very basic Twitter reader built in Python. If you’ve got any questions or comments, feel free to leave them below or head on over to our forums.

Flex & Actionscript Singleton Model Class

In many of the projects and applications I build with Flex I use a singleton for the Model – we’ve talked about Singletons in the past here. Whether this is the preferred method of handling a model is a matter of opinion so I won’t be discussing it. However, I do want to share the model class that I typically use. Actionscript lacks a real static constructor, used for creating a single instance of a class, which means creating a nice singleton takes a bit more work.

To create the singleton I take advantage of using a local class definition inside of my model Actionscript file. From my understanding the local class, it is only visible and valid inside of the file. Also I owe props to some blog for pointing this trick out but I can’t remember the blog – sorry. This means we can ensure that the only instance of the model is created inside of the class. Let’s take a look of the entire code below and we can make a little more sense of it.

package
{
  [Bindable]
  public class MainModel
  {
    private static var _instance:MainModel = new MainModel(ModelEnforcer);
   
    public static function getInstance():MainModel
    {
      return _instance;
    }
   
    public function MainModel(enforcer:Class)
    {
      if(enforcer != ModelEnforcer) {
        throw new Error("Use MainModel.getInstance to access model");
      }
    }
 
  }
}

class ModelEnforcer {}

Ok so above we have the ever so popular GetInstance method which is what all external files will use to get an instance of the model. This will check if the local static variable for the single instance is populated and if not calls the constructor which takes the aforementioned local class. Inside the constructor you can initialize whatever you need to and basically everything else in the class is going to a public variable or a convenience method.

To summarize, we have a local class that makes sure that the only instance is created inside the MainModel class. And, of course, use GetInstance to grab the instance. That is pretty much it. If you have any questions or want to simply comment on using this method feel free to leave a comment.

Flex & Actionscript Singleton Model Class

In many of the projects and applications I build with Flex I use a singleton for the Model – we’ve talked about Singletons in the past here. Whether this is the preferred method of handling a model is a matter of opinion so I won’t be discussing it. However, I do want to share the model class that I typically use. Actionscript lacks a real static constructor, used for creating a single instance of a class, which means creating a nice singleton takes a bit more work.

To create the singleton I take advantage of using a local class definition inside of my model Actionscript file. From my understanding the local class, it is only visible and valid inside of the file. Also I owe props to some blog for pointing this trick out but I can’t remember the blog – sorry. This means we can ensure that the only instance of the model is created inside of the class. Let’s take a look of the entire code below and we can make a little more sense of it.

package
{
  [Bindable]
  public class MainModel
  {
    private static var _instance:MainModel = new MainModel(ModelEnforcer);
   
    public static function getInstance():MainModel
    {
      return _instance;
    }
   
    public function MainModel(enforcer:Class)
    {
      if(enforcer != ModelEnforcer) {
        throw new Error("Use MainModel.getInstance to access model");
      }
    }
 
  }
}

class ModelEnforcer {}

Ok so above we have the ever so popular GetInstance method which is what all external files will use to get an instance of the model. This will check if the local static variable for the single instance is populated and if not calls the constructor which takes the aforementioned local class. Inside the constructor you can initialize whatever you need to and basically everything else in the class is going to a public variable or a convenience method.

To summarize, we have a local class that makes sure that the only instance is created inside the MainModel class. And, of course, use GetInstance to grab the instance. That is pretty much it. If you have any questions or want to simply comment on using this method feel free to leave a comment.

Running a Method After A Delay on iPhone or Mac

In nearly every programming language there is a way to delay a method call. Objective-C is no different. They have built in a few simple methods to achieve this. We are going take a look at one of these methods today, all which reside in NSObject. This means any class you create will have the ability to call these methods. The method we are going to take a gander at is - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay, got the love the Objective-C method names.

This method is pretty self explanatory thanks to the super long name. Basically, we are going to run a method and pass in the object as the parameter for the method after a certain amount of time (in seconds). Okay, imagine we have built an application which has a label that we want to change the text of after 5 seconds, why? I don’t know, if the label keeps the same text for more than 5 seconds it will self destruct, anyway I digress. So, we create a method to change the text to something like the following:

(void)changeText:(NSString *)text
{
  myLabel.text = text;
}

The new method is about as simple as it gets, it changes the label’s text to the passed in value. Now, in order to call this on a delay we need to use our aforementioned method, - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay. In order to call our change text method with this it would look something like below.

[self performSelector:@selector(changeText:) withObject:@"Hello" afterDelay:5];

This pretty much covers it. One note is that say you have a method that doesn’t take a parameter like the one below.

(void)changeText
{
  myLabel.text = @"Hello";
}

Then if you want to call the method you pass in nil for the withObject argument, like the following:

[self performSelector:@selector(changeText) withObject:nil afterDelay:5];

Well that pretty much sums it up. You should now be able to call code after a delay. If you have any questions feel free to leave a comment or head on over to the forums.

Running a Method After A Delay on iPhone or Mac

In nearly every programming language there is a way to delay a method call. Objective-C is no different. They have built in a few simple methods to achieve this. We are going take a look at one of these methods today, all which reside in NSObject. This means any class you create will have the ability to call these methods. The method we are going to take a gander at is - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay, got the love the Objective-C method names.

This method is pretty self explanatory thanks to the super long name. Basically, we are going to run a method and pass in the object as the parameter for the method after a certain amount of time (in seconds). Okay, imagine we have built an application which has a label that we want to change the text of after 5 seconds, why? I don’t know, if the label keeps the same text for more than 5 seconds it will self destruct, anyway I digress. So, we create a method to change the text to something like the following:

(void)changeText:(NSString *)text
{
  myLabel.text = text;
}

The new method is about as simple as it gets, it changes the label’s text to the passed in value. Now, in order to call this on a delay we need to use our aforementioned method, - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay. In order to call our change text method with this it would look something like below.

[self performSelector:@selector(changeText:) withObject:@"Hello" afterDelay:5];

This pretty much covers it. One note is that say you have a method that doesn’t take a parameter like the one below.

(void)changeText
{
  myLabel.text = @"Hello";
}

Then if you want to call the method you pass in nil for the withObject argument, like the following:

[self performSelector:@selector(changeText) withObject:nil afterDelay:5];

Well that pretty much sums it up. You should now be able to call code after a delay. If you have any questions feel free to leave a comment or head on over to the forums.

Python Tutorial – Batch Image Resizing

Every once and a while I come across a simple task that deserves a script. Instead of using a language I know, this is often a great opportunity to pick up a new language or get a refresher on one I haven’t used in a long time. In this case, I needed to resize an entire directory of images. There are tons of free tools out there to do this, but where’s the fun in that? Also, I could have whipped this tool up very quickly in a language I know, like C#, however I haven’t used Python in several years and I decided it was time for a refresher.

For this tutorial, I’m using Python 2.6.5 and the Python Image Library (PIL). If you’re reading this tutorial, I’m sure you’ve got the first one installed and ready to go. The second one, PIL, is a free download.

I decided to create a simple command line application for this task. It will take three arguments: -d, -w, and -h. -d is the directory where your images are located. -w is the output image’s desired width. -h is the output image’s desired height. It will be used like this:

> python BatchImageResize.py -d "C:\MyImages" -w 1024 -h 768

The first thing we’re going to have to do is parse the command line arguments. Fortunately Python comes with a function, getopt, that makes this very simple.

import getopt, sys

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

getopt requires two parameters. The first is the list of arguments passed into the script. We’re skipping the first argument because that’s just the name of the script being executed. The second is the shorthand notation for each command line option. Since each option requires extra information, like a directory path, we need to stick a colon after each one. If the option were just a flag, with no extra info, the colon would be omitted. This returns two things. The first is a collection of tuples containing the argument and the extra information. The second contains all the other arguments that didn’t match what we were looking for. getopt has an optional third parameter that lets you specify a long name for each argument, but it’s not necessary for this tutorial.

Now that we’ve got the command line arguments parsed, we need to read the values into some variables. And while we’re at it, we might as well stick in a little bit of validation.

import getopt, sys

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

directory = ""
width = –1
height = –1

# Read the command line arguments
for opt, arg in opts:
  if opt == ‘-d’:
    directory = arg
  elif opt == ‘-w’:
    width = int(arg)
  elif opt == ‘-h’:
    height = int(arg)

# Check that the options were all set
if directory == "" or width == –1 or height == –1:
  print "Invalid command line arguments.\
  -d [directory] -w [width] -h [height] required"

  exit())

All we’re doing here is iterating through every specified option and saving the value to some variables. The width and height will need to be converted to integers for later use.

We’re now ready to actually convert all the images.

import os, getopt, sys, Image

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

directory = ""
width = –1
height = –1

# Read the command line arguments
for opt, arg in opts:
  if opt == ‘-d’:
    directory = arg
  elif opt == ‘-w’:
    width = int(arg)
  elif opt == ‘-h’:
    height = int(arg)

# Check that the options were all set
if directory == "" or width == –1 or height == –1:
  print "Invalid command line arguments.\
  -d [directory] -w [width] -h [height] required"

  exit()
 
# Iterate through every image in the directory and resize them
for file in os.listdir(directory):
  print "Resizing image " + file
  # Open the image
  img = Image.open(directory + "\\" + file)
  # Resize it
  img = img.resize((width, height), Image.BILINEAR)
  # Save it back to disk
  img.save(directory + "\\resized" + file)

This is actually the entire contents of the script. We first iterate through every file in the specified directory. We then open, resize, and save the image using PIL. There are several resizing techniques available, however I chose Bilinear because it yields perfectly satisfactory results. Every file will be saved to the same location it came from except with “resized” appended on the beginning.

And that’s it. Python has some great support for easily and quickly creating powerful command line applications. Thanks to the active community of developers there are libraries, like PIL, that will do pretty much anything you’ll need.

Python Tutorial – Batch Image Resizing

Every once and a while I come across a simple task that deserves a script. Instead of using a language I know, this is often a great opportunity to pick up a new language or get a refresher on one I haven’t used in a long time. In this case, I needed to resize an entire directory of images. There are tons of free tools out there to do this, but where’s the fun in that? Also, I could have whipped this tool up very quickly in a language I know, like C#, however I haven’t used Python in several years and I decided it was time for a refresher.

For this tutorial, I’m using Python 2.6.5 and the Python Image Library (PIL). If you’re reading this tutorial, I’m sure you’ve got the first one installed and ready to go. The second one, PIL, is a free download.

I decided to create a simple command line application for this task. It will take three arguments: -d, -w, and -h. -d is the directory where your images are located. -w is the output image’s desired width. -h is the output image’s desired height. It will be used like this:

> python BatchImageResize.py -d "C:\MyImages" -w 1024 -h 768

The first thing we’re going to have to do is parse the command line arguments. Fortunately Python comes with a function, getopt, that makes this very simple.

import getopt, sys

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

getopt requires two parameters. The first is the list of arguments passed into the script. We’re skipping the first argument because that’s just the name of the script being executed. The second is the shorthand notation for each command line option. Since each option requires extra information, like a directory path, we need to stick a colon after each one. If the option were just a flag, with no extra info, the colon would be omitted. This returns two things. The first is a collection of tuples containing the argument and the extra information. The second contains all the other arguments that didn’t match what we were looking for. getopt has an optional third parameter that lets you specify a long name for each argument, but it’s not necessary for this tutorial.

Now that we’ve got the command line arguments parsed, we need to read the values into some variables. And while we’re at it, we might as well stick in a little bit of validation.

import getopt, sys

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

directory = ""
width = –1
height = –1

# Read the command line arguments
for opt, arg in opts:
  if opt == ‘-d’:
    directory = arg
  elif opt == ‘-w’:
    width = int(arg)
  elif opt == ‘-h’:
    height = int(arg)

# Check that the options were all set
if directory == "" or width == –1 or height == –1:
  print "Invalid command line arguments.\
  -d [directory] -w [width] -h [height] required"

  exit())

All we’re doing here is iterating through every specified option and saving the value to some variables. The width and height will need to be converted to integers for later use.

We’re now ready to actually convert all the images.

import os, getopt, sys, Image

# Parse the command line arguments
opts, args = getopt.getopt(sys.argv[1:], "d:w:h:")

directory = ""
width = –1
height = –1

# Read the command line arguments
for opt, arg in opts:
  if opt == ‘-d’:
    directory = arg
  elif opt == ‘-w’:
    width = int(arg)
  elif opt == ‘-h’:
    height = int(arg)

# Check that the options were all set
if directory == "" or width == –1 or height == –1:
  print "Invalid command line arguments.\
  -d [directory] -w [width] -h [height] required"

  exit()
 
# Iterate through every image in the directory and resize them
for file in os.listdir(directory):
  print "Resizing image " + file
  # Open the image
  img = Image.open(directory + "\\" + file)
  # Resize it
  img = img.resize((width, height), Image.BILINEAR)
  # Save it back to disk
  img.save(directory + "\\resized" + file)

This is actually the entire contents of the script. We first iterate through every file in the specified directory. We then open, resize, and save the image using PIL. There are several resizing techniques available, however I chose Bilinear because it yields perfectly satisfactory results. Every file will be saved to the same location it came from except with “resized” appended on the beginning.

And that’s it. Python has some great support for easily and quickly creating powerful command line applications. Thanks to the active community of developers there are libraries, like PIL, that will do pretty much anything you’ll need.

Loading XML Through XNA Content Pipeline

XNA is quite possibly one of the most robust game programming frameworks out there. You can do nearly anything with it, and one of the reasons it is so flexible is its “Content Pipeline”. But sometimes it can be a bit tricky to use this feature, requiring us to do bit more work. But in the end, it helps to use the Content Pipeline. Luckily today we are going over how to use it to load in some XML.

A quick google search will reveal that loading in XML with C# and XNA can be a bit more complicated that it seems. There are several ways to accomplish XML integration, all dependent on your needs. Today we are going to go over the simplest way to load XML in XNA using the fancy Content Pipeline.

For the best viewing, use full screen mode.

<!–

Get Adobe Flash player

<!–