You are on page 1of 776

Flickr Hacks

By Paul Bausch, Jim Bumgardner


...............................................
Publisher: O'Reilly
Pub Date: February 2006
Print ISBN-10: 0-596-10245-3
Print ISBN-13: 978-0-59-610245-6
Pages: 364

Table of C ontents | I ndex

O ver two million regis tered Flic kr us ers and c ounting have
dis c overed the eas e and fun of organizing their photo libraries ,
s howing off their favorite pic tures to the world, and s ec urely
s haring their private pic tures with friends , family, or ad hoc
groups . But Flic kr's own plethora of intuitive menus , options ,
and features jus t s c ratc hes the s urfac e.

Flickr Hacks goes beyond the bas ic s of s toring, s orting, and


s haring your photos to the muc h bigger playground of what's
pos s ible. Whether you're a beginner looking to manage your
metadata and play with tags , or a programmer in need of a
detailed referenc e of Flic kr A P I methods , you'll find what you're
looking for here. I n addition to getting under the hood of s ome of
the mos t popular third- party Flic kr toys already in the wild,
you'll learn how to:

P os t photos to your blog direc tly from your


c ameraphone

M as h up your own photos or others ' public pic tures into


c us tom mos aic s , c ollages , s liding puzzles , s lides hows ,
or rans om notes

Bac k up your Flic kr library to your des ktop, and s ave


the c omments too

Set random des ktop bac kgrounds and build your own
Flic kr s c reens aver

G eotag your photos and map your c ontac ts

D ownload a lis t of photos and make a c ontac t s heet

M ake your own Flic kr- s tyle tag c loud to vis ualize the
frequenc y of c ommon tags

Build a c olor pic ker with a dynamic c olor wheel of Flic kr


photos

Feed photos to your web s ite and s ubs c ribe to c us tom


Flic kr feeds us ing RSS
Talk to the Flic kr A P I us ing your web brows er, P erl, or
P H P ; authentic ate yours elf and other us ers ; and build
c us tom A P I applic ations
Flickr Hacks
By Paul Bausch, Jim Bumgardner
...............................................
Publisher: O'Reilly
Pub Date: February 2006
Print ISBN-10: 0-596-10245-3
Print ISBN-13: 978-0-59-610245-6
Pages: 364

Table of C ontents | I ndex

Copyright
Preface
Why Flickr Hacks?
How to Use This Book
How to Run the Hacks
How This Book Is Organized
Conventions Used in This Book
Using Code Examples
How to Contact Us
Got a Hack?

Safari Enabled
Chapter 1. Sharing Photos
Hacks 1-9
Hack 1. Store, Sort, and Share Your Photos
Hack 2. Control Who Sees Your Photos
Hack 3. Manage Image Metadata
Hack 4. Resize Photos for Flickr
Hack 5. Add Photos Quickly
Hack 6. Post Pictures from Your Cell Phone
Hack 7. Feed Your Latest Photos to Your Web Site
Hack 8. Make a Photo Gallery in 30 Seconds or Less
Hack 9. Post Photos to Your Blog
Chapter 2. Tagging Photos
Hacks 10-14
Hack 10. Describe Your Photos
Hack 11. Play w ith Tags
Hack 12. Geotag Your Photos
Hack 13. Exploit Compound Tags
Hack 14. Make a Flickr-Style Tag Cloud
Chapter 3. View ing Photos
Hacks 15-23
Hack 15. Add Flickr Search to Firefox
Hack 16. Find Pictures You Can Reuse Legally
Hack 17. Subscribe to Flickr
Hack 18. Rate Photos
Hack 19. Travel w ith Flickr
Hack 20. Build a Custom Flickr Feed
Hack 21. Set Random Desktop Backgrounds
Hack 22. Build a Flickr Screensaver
Hack 23. View Flickr Photos on TiVo
Chapter 4. Community
Hacks 24-29
Hack 24. Add and Track Contacts
Hack 25. Track Your Friends' Favorites
Hack 26. Find Your Friends' Favorite Tags
Hack 27. Map Your Contacts
Hack 28. Find Flickrites in Your Mac Address Book
Hack 29. Surf Your Contacts
Chapter 5. Maintenance
Hacks 30-36
Hack 30. Back Up Your Photos
Hack 31. Back Up Photo Comments
Hack 32. Make a Contact Sheet
Hack 33. Dow nload a List of Photos
Hack 34. Cache Photos Locally
Hack 35. Edit Photos as a Batch
Hack 36. Clean the (Group) Pool
Chapter 6. API Basics
Hacks 37-42
The API Page
API Methods
API Keys and Secrets
Identifying Users
Identifying Groups
Identifying Photos
Deconstructing Flickr URLs
Talking to the API
Hack 37. Talk to the API w ith Your Web Brow ser
Hack 38. Talk to the API w ith Perl
Hack 39. Talk to the API w ith PHP
Hack 40. Authenticate Yourself
Hack 41. Authenticate Users
Hack 42. Build a Custom Upload Script
Chapter 7. Custom Applications
Hacks 43-50
Hack 43. Mash Up Your Photos
Hack 44. Find the Dominant Color of an Image
Hack 45. Make a Color Picker
Hack 46. Make a Motivational Poster and Other
Sw ag
Hack 47. Make a Ransom Note
Hack 48. Make a Slider Puzzle
Hack 49. Make a Photo Mosaic
Hack 50. Make a Slideshow
Index
C opyright © 2 0 0 6 O 'Reilly M edia, I nc . A ll rights res erved.

P rinted in the U nited States of A meric a.

P ublis hed by O 'Reilly M edia, I nc ., 1 0 0 5 G ravens tein H ighway


N orth, Sebas topol, C A 9 5 4 7 2 .
Preface
I n February 2 0 0 4 , a tiny s tartup in Vanc ouver c alled L udic orp
launc hed a web s ite for s haring photos c alled Flic kr. U s ing s ome
of the tools they'd built for their primary produc t (a web game
c alled G ame N everending), L udic orp quic kly c hanged the way
millions of people s hare photos . J us t one year and one month
after its launc h, web giant Yahoo! purc has ed Flic krwith rumors
putting the pric e tag at s omewhere around $ 3 0 million. Yahoo! is
now working diligently to "Flic krize" all of its features by
adapting the innovations that Flic kr brought to photo s haring to
Yahoo! 's exis ting features for s earc hing, s hopping, and travel
planning.

So, what exac tly did Flic kr ac c omplis h that attrac ted millions of
us ers and has an es tablis hed web c ompany c hanging the way it
does bus ines s ? T he ans wer is n't an eas y one, but s tudying how
Flic kr has taken the world by s torm c an give us s ome indic ation
of where the Web is headed.

O ne innovation that Flic kr pioneered is the ac t of tagging digital


c ontent. I ns tead of impos ing a c ategory s ys tem, Flic kr lets
individual photographers do the hard work of c las s ifying photos .
For example, a photo of a c ar c an be tagged with words s uc h as
car or automobile, or with more s pec ific des c riptive terms s uc h as
Honda, convertible, or s hiny. T hen, others interes ted in pic tures
of c ars , c onvertibles , or s hiny things c an brows e thos e tags to
find photos that might interes t them. Tagging is a c lever way to
loos ely c onnec t photos without a s truc tured c ategorization
s ys tem.

I n addition to tagging, Flic kr allows members to c reate ad hoc


groups to s hare photos of s pec ific s ubjec ts . A famous frivolous
example is the Flic kr Squared C irc le group
(http://www.flic kr.c om/groups /c irc le/), whic h formed to s hare
photos of c irc ular objec ts c ropped to s quares . A nyone c an
partic ipate, and the group has built a library of over 2 2 ,0 0 0
s quared c irc le photographs at the time of this writing.

I n addition to c ollaborating with s trangers on Flic kr, you c an add


friends and family to your Flic kr c ontac ts lis t to eas ily keep
trac k of new photos pos ted by people you know. I t's a s imple but
powerful way to s hare experienc es with people you c are about.

A nother innovation that s ets Flic kr apart from other photo-


s haring s ervic es is its open A P I . Flic kr's open arc hitec ture
allows outs ide developers to c ode features for Flic kr and s how
Flic kr photos on other web s ites and ins ide other applic ations .
O ne s triking example of the A P I in ac tion is J im Bumgardner's
vis ualization of over 1 ,0 0 0 images in the Flic kr Squared C irc le
pool, s hown in Figure P - 1 .

Figure P-1. Flickr squared circle poster


T he individual photographers c ontributing to the Squared C irc le
group had no idea their photos would end up in a c olorful
montage, but Flic kr's A P I made the vis ualization pos s ible. M any
s ites and applic ations have already integrated with Flic kr thanks
to the A P I , and you'll s ee many examples of how people are
us ing the A P I in this book.

T he power of s haring photos ins tantly via the Web hit


mains tream c ons c ious nes s s oon after bombs ripped through
L ondon's s ubway on J uly 7 , 2 0 0 5 . A s televis ion news networks
s c rambled to get images of the bombing on T V, pic tures were
already appearing on Flic kr, thanks to people with c ell phone
c ameras at the s c ene. T he photo by A dam Stac ey s hown in
Figure P - 2 bec ame an early ic on of the attac ks , and you c an s till
view this photo on Flic kr
(http://www.flic kr.c om/photos /qwghlm/2 4 2 3 0 2 3 9 /in/pool-
bomb/) and read the c omments pos ted.

Figure P-2. London bombing photo by Adam


Stacey
D uring a horrific inc ident, when people were des perate for any
information they c ould glean about the s ituation, Flic kr provided
a way to s hare images from the event ins tantly, while it was
happening. I n addition, Flic kr provided a s pac e where people
c ould dis c us s the event and form groups to s hare bombing
photos , and Flic kr's tagging features allowed others to find
bomb- related photos quic kly.

While mos t of the photo s haring that happens on a daily bas is at


Flic kr is n't nearly as s erious as the photos s hared on J uly 7 ,
2 0 0 5 , the L ondon bombings let the world know that the features
Flic kr provides make it more important than a s imple web toy.
Why Flickr Hacks?
T he term hacking has a bad reputation in the pres s . T hey us e it
to refer to s omeone who breaks into s ys tems or wreaks havoc
with c omputers as their weapon. A mong people who write c ode,
though, the term hack refers to a "quic k- and- dirty" s olution to a
problem, or a c lever way to get s omething done. A nd the term
hacker is taken very muc h as a c ompliment, referring to s omeone
as being creative, having the tec hnic al c hops to get things done.
T he H ac ks s eries is an attempt to rec laim the word, doc ument
the good ways people are hac king, and pas s the hac ker ethic of
c reative partic ipation on to the uninitiated. Seeing how others
approac h s ys tems and problems is often the quic kes t way to
learn about a new tec hnology.

T his book aims to help you gain a deeper apprec iation and
unders tanding of the c reativity Flic kr has made pos s ible by
s howing you s ome of the many ways people are us ing and
extending Flic kr on their own. By unders tanding Flic kr, you'll
have a better s ens e of where the Web is headed, and how you
c an partic ipate.
How to Use This Book
You c an read this book from c over to c over if you like, but eac h
hac k s tands on its own, s o feel free to brows e and jump to the
different s ec tions that interes t you mos t. I f there's a
prerequis ite you need to know about, a c ros s - referenc e will
guide you to the right hac k.
How to Run the Hacks
T he programmatic hac ks in this book run either on the c ommand
line (that's Terminal for M ac O S X folks , or the D O S c ommand
window for Windows us ers ) or as C G I s c ripts or P H P
s c ripts dynamic pages living on your web s ite, ac c es s ed through
your web brows er.

Command-Line Scripts

Running a hac k on the c ommand line invariably involves the


following s teps :

1. Type the program into a garden- variety text editor:


N otepad on Windows , TextE dit on M ac O S X, vi or Emacs
on U nix/L inux, or anything els e of the s ort. Save the file
as direc tedus ually as s criptname.pl (the .pl bit s tands for
P erl, the predominant programming language us ed in
Flickr Hacks ).

A lternately, you c an download the c ode for all of the


hac ks online at
http://www.oreilly.c om/c atalog/flic krhks /, where you'll
find a ZI P arc hive filled with individual s c ripts already
s aved as text files .

2. G et to the c ommand line on your c omputer or remote


s erver. I n M ac O S X, launc h Terminal (A pplic ations
U tilities Terminal). I n Windows , c lic k the Start
button, s elec t Run, type command, and hit the E nter/Return
key on your keyboard. I n U nix... well, we'll jus t as s ume
you know how to get to the c ommand line.

3. N avigate to where you s aved the s c ript at hand. T his


varies from operating s ys tem to operating s ys tem, but it
us ually involves a c ommand like cd ~/Desktop (that's
your D es ktop on the M ac ).

4. I nvoke the s c ript by running the programming


language's interpreter (e.g., P erl) and feeding it the
s c ript (e.g., s criptname.pl), like s o:

perl
scriptname.pl

5. M os t often, you'll als o need to pas s along s ome


parameters your s earc h query, the number of res ults
you'd like, and s o forth. Simply drop them in after the
s c ript name, enc los ing them in quotes if they're more
than one word or if they inc lude an odd c harac ter or
three:

perl
scriptname.pl '"much ado about nothing" script' 10

6. T he res ults of your s c ript are almos t always s ent


s traight bac k to the c ommand- line window in whic h
you're working, like s o:

> perl
scriptname.pl '"much ado about nothing" script' 10

1. "Amazon.com: Books: Much Ado About Nothing: Screenplay


2. "Much Ado About Nothing Script" [http://www.signal42.co
...

T he elllps is (...) bit s ignifies that


we've c ut off the output for
brevity's s ake.

7. To s top output s c rolling off your s c reen fas ter than you
c an read it, on mos t s ys tems you c an pipe (read:
redirec t) the output to a little program c alled more:

perl
scriptname.pl
| more

8. H it the E nter/Return key on your keyboard to s c roll


through line by line, or us e the s pac ebar to leap through
page by page.

You'll als o s ometimes want to direc t output to a file for


s afekeeping, importing into your s preads heet
applic ation, or dis playing on your web s ite. T his is as
eas y as :

perl
scriptname.pl
>
output_filename.txt
9. A nd to pour s ome input into your s c ript from a file,
s imply do the oppos ite:

perl
scriptname.pl
<
input_filename.txt

D on't worry if you c an't remember all of this ; eac h


relevant hac k has a Sec tion 2 .5 .3 s ec tion that s hows
you jus t how it's done.

CGI Scripts

C G I s c ripts programs that run on your web s ite and produc e


pages dynamic allyare a little more c omplic ated if you're not
us ed to them. While fundamentally they're the s ame s orts of
s c ripts as thos e run on the c ommand line, they are more
troubles ome bec aus e s etups vary s o widely. Your c ontent might
be hos ted on your own s erver, on an I nternet s ervic e provider's
(I SP 's ) s erver, on a c orporate intranet s erver, or anything in
between.

Sinc e going through every pos s ibility is beyond the s c ope of this
(or any) book, if you need help you s hould c hec k your I SP 's
knowledge bas e or c all their tec hnic al s upport department, or
as k your loc al s ys tem adminis trator.

G enerally, though, the methodology is the s ame:

1. Type the program into a garden- variety text editor:


N otepad on Windows , TextE dit on M ac O S X, vi or Emacs
on U nix/L inux, or anything els e of the s ort. Save the file
as direc tedus ually as s criptname.cgi (the .cgi bit reveals
that you're dealing with a C G I that's C ommon G ateway
I nterfac es c ript).

A lternately, you c an download the c ode for all of the


hac ks online at
http://www.oreilly.c om/c atalog/flic krhks /, where you'll
find a ZI P arc hive filled with individual s c ripts already
s aved as text files .

2. M ove the s c ript over to wherever your web s ite lives .


You s hould have s ome direc tory on a s erver s omewhere
in whic h all of your web pages (all thos e .html files ) and
images (files ending in .j pg, .gif, etc .) live. Within this
direc tory, you'll probably s ee s omething c alled a cgi-bin
direc tory: this is where C G I s c ripts mus t us ually live in
order to be run rather than jus t dis played in your web
brows er when you vis it the pages that c ontain them.

3. You us ually need to bles s C G I s c ripts as exec utableto


be run rather than dis played. J us t how you do this
depends on the operating s ys tem of your s erver. I f
you're on a U nix/L inux or M ac O S X s ys tem, this us ually
entails typing the following on the c ommand line:

chmod 755
scriptname.cgi

4. N ow you s hould be able to point your web brows er at the


s c ript and have it run as expec ted, behaving in a manner
s imilar to that des c ribed in the Sec tion 2 .5 .3 s ec tion of
the hac k at hand.

J us t what U RL you us e, onc e again, varies wildly. I t


s hould, however, look s omething like this :
http://www.your_domain.com/cgi-bin/s criptname.cgi,
where your_domain.com is your web s ite domain, cgi-bin
is the direc tory in whic h your C G I s c ripts live, and
s criptname.cgi is the s c ript its elf.

I f you don't have a domain and your s ite is hos ted by an


I SP, the U RL is more likely to look like this :
http://www.your_is p.com/~your_us ername/cgi-
bin/s criptname.cgi, where your_is p.com is your I SP 's
domain, ~your_us ername is your us ername at the I SP,
cgi-bin is the direc tory in whic h your C G I s c ripts live,
and s criptname.cgi is the s c ript its elf.

I f you c ome up with s omething c alled an "I nternal Server E rror"


or s ee the error c ode 5 0 0 , s omething's gone wrong s omewhere
in the proc es s . A t this point you c an take a c rac k at debugging
(read: s haking the bugs out) yours elf, or as k your I SP or s ys tem
adminis trator for help. D ebugginges pec ially C G I debuggingc an
be a little more than the average newbie c an bear, but there is
help in the form of a famous Frequently A s ked Q ues tion (FA Q ):
"T he I diot's G uide to Solving P erl C G I P roblems ." Searc h for it
and s tep through it as direc ted.

PHP Scripts

P H P s c ripts programs in the P H P language that run on your web


s ite and produc e pages dynamic allyare s et up in a manner very
s imilar to C G I s c ripts , but are generally eas ier to manage.
U nlike C G I s c ripts , the files do not need to live in a s pec ial cgi-
bin/ direc tory, but c an c oexis t with your H T M L files . A ls o you
us ually don't have to c hange the file permis s ions .

M os t of the s c ripts in this book require P H P Vers ion 4 , whic h is


c ommonly available from mos t hos ting providers .

For more information about P H P, c hec k out the online manual at


http://www.php.net/manual/en/.

Learning to Code

Fanc y trying your hand at a s pot of programming? O 'Reilly's


bes t- s elling Learning Perl
(http://www.oreilly.c om/c atalog/lperl3 /), by Randal L . Sc hwartz
and Tom P hoenix, provides a good s tart. A pply what you learn to
unders tanding and us ing the hac ks in this book, perhaps even
taking on the Sec tion 1 .8 .3 s ec tions to tweak and fiddle with the
s c ripts . T his is a us eful way to get s ome programming under
your belt, s inc e it's always a little eas ier to learn how to program
when you have a tas k to ac c omplis h and exis ting c ode to leaf
through.
How This Book Is Organized
T he book is divided into s even c hapters , organized by s ubjec t:

C hapter 1

T his c hapter s hows you how to mas ter the bas ic s of


s haring photos on Flic kr, inc luding editing images for
Flic kr, managing extended information about your
photos , and pos ting direc tly from your c ell phone. You'll
als o find an overview of tools to help you upload photos
more effic iently and a look at ways to us e Flic kr to
publis h photos on your own web s ite.

C hapter 2

Flic kr is famous for tagging. T his c hapter s hows how to


take advantage of tagging for organizing and public izing
your photos . You'll als o s ee s ome unique ways people
are us ing tagging to group photos by loc ation, and you'll
find s ome external games that us e Flic kr's tagging
features for fun.

C hapter 3

T his c hapter introduc es you to s ome unexpec ted ways


to find and view Flic kr photos . You'll get an overview of
the many ways Flic kr us es RSS to dis tribute photos , a
look at how you c an us e Flic kr mobile to s tay in touc h on
the go, and the lowdown on how to view Flic kr photos on
your T V.

C hapter 4

U s e the hac ks in this c hapter to learn more about your


Flic kr c ommunity. I n addition to the bas ic s of adding and
viewing c ontac ts , you'll find hac ks that s how how to view
your c ontac ts on a map and brows e their non- Flic kr
ac tivities . You'll als o s ee how to find out whic h tags are
mos t popular among your friends and whic h photos
they're marking as their favorites .

C hapter 5

I n this c hapter, you'll s ee how Flic kr experts manage


large c ollec tions of photos and maintain large Flic kr
groups . You'll find out how to bac k up your Flic kr photos
for s afekeeping and how to c reate a c ontac t s heet of
your Flic kr photos for quic k referenc e.

C hapter 6

T his c hapter introduc es you to the Flic kr A P I , whic h is a


bac k door that Flic kr provides for developers . You c an
us e the hac ks in this c hapter as building bloc ks for your
own Flic kr applic ations . You'll s ee c onc rete examples for
talking with the A P I , authentic ating with the A P I , and
us ing exis ting tools for rapid Flic kr development.
C hapter 7

See how people are us ing Flic kr photos in their own


applic ations and games , and have a bit of fun in the
proc es s . T his c hapter s hows how to turn your photos
into beautiful c ollages , rans om notes , motivational
pos ters , s liding puzzles , and more.
Conventions Used in This Book
T he following is a lis t of the typographic al c onventions us ed in
this book:

I talic

U s ed for emphas is and new terms where they are


defined, and to indic ate U nix utilities , U RL s , filenames ,
filename extens ions , and direc tory/folder names . For
example, a path in the files ys tem will appear as
/Developer/Applications .

Constant width

U s ed to s how c ode examples , the c ontents of files , and


c ons ole output, as well as the names of variables ,
c ommands , and other c ode exc erpts .

Constant width bold

U s ed to highlight portions of c ode, either for emphas is or


to indic ate text that s hould be typed by the us er.

Constant width italic

U s ed in c ode examples to s how s ample text to be


replac ed with your own values .
Gray type

G ray text is us ed to indic ate a c ros s - referenc e within


the text.

You s hould pay s pec ial attention to notes s et apart from the text
with the following ic ons :

T his is a tip, s ugges tion, or general note.


I t c ontains us eful s upplementary
information about the topic at hand.

T his is a warning or note of c aution, often


indic ating that your money or your privac y
might be at ris k.

T he thermometer ic ons , found next to eac h hac k, indic ate the


relative c omplexity of the hac k:
beginner moderate expert
Using Code Examples
T his book is here to help you get your job done. I n general, you
may us e the c ode in this book in your programs and
doc umentation. You do not need to c ontac t us for permis s ion
unles s you're reproduc ing a s ignific ant portion of the c ode. For
example, writing a program that us es s everal c hunks of c ode
from this book does not require permis s ion. Selling or
dis tributing a C D - RO M of examples from O 'Reilly books does
require permis s ion. A ns wering a ques tion by c iting this book and
quoting example c ode does not require permis s ion.
I nc orporating a s ignific ant amount of example c ode from this
book into your produc t's doc umentation does require permis s ion.

We apprec iate, but do not require, attribution. A n attribution


us ually inc ludes the title, author, publis her, and I SBN . For
example: "Flickr Hacks by P aul Baus c h and J im Bumgardner.
C opyright 2 0 0 6 O 'Reilly M edia, I nc ., 0 - 5 9 6 - 1 0 2 4 5 - 3 ."

I f you feel your us e of c ode examples falls outs ide fair us e or the
permis s ion given above, feel free to c ontac t us at
permis s ions @ oreilly.c om.
How to Contact Us
We have tes ted and verified the information in this book to the
bes t of our ability, but you may find that features have c hanged
(or even that we have made mis takes ! ). A s a reader of this book,
you c an help us to improve future editions by s ending us your
feedbac k. P leas e let us know about any errors , inac c urac ies ,
bugs , mis leading or c onfus ing s tatements , and typos that you
find anywhere in this book.

P leas e als o let us know what we c an do to make this book more


us eful to you. We take your c omments s erious ly and will try to
inc orporate reas onable s ugges tions into future editions . You c an
write to us at:

O 'Reilly M edia, I nc .
1 0 0 5 G ravens tein H wy N .
Sebas topol, C A 9 5 4 7 2
(8 0 0 ) 9 9 8 - 9 9 3 8 (in the U .S. or C anada)
(7 0 7 ) 8 2 9 - 0 5 1 5 (international/loc al)
(7 0 7 ) 8 2 9 - 0 1 0 4 (fax)

To as k tec hnic al ques tions or to c omment on the book, s end


email to:

bookques tions @ oreilly.c om

T he web s ite for Flickr Hacks lis ts examples , errata, and plans for
future editions . You c an find this page at:

http://www.oreilly.c om/c atalog/flic krhks /

For more information about this book and others , s ee the


O 'Reilly web s ite:
http://www.oreilly.c om
Got a Hack?
To explore H ac ks books online or to c ontribute a hac k for future
titles , vis it:

http://hac ks .oreilly.c om
Safari Enabled

When you s ee a Safari® E nabled ic on on


the c over of your favorite tec hnology book, that means the book
is available online through the O 'Reilly N etwork Safari Books helf.

Safari offers a s olution that's better than e- Books . I t's a virtual


library that lets you eas ily s earc h thous ands of top tec h books ,
c ut and pas te c ode s amples , download c hapters , and find quic k
ans wers when you need the mos t ac c urate, c urrent information.
Try it for free at http://s afari.oreilly.c om.
Chapter 1. Sharing Photos

H ac ks 1 - 9

H ac k 1 . Store, Sort, and Share Your P hotos

H ac k 2 . C ontrol Who Sees Your P hotos

H ac k 3 . M anage I mage M etadata

H ac k 4 . Res ize P hotos for Flic kr

H ac k 5 . A dd P hotos Q uic kly

H ac k 6 . P os t P ic tures from Your C ell P hone

H ac k 7 . Feed Your L ates t P hotos to Your Web Site

H ac k 8 . M ake a P hoto G allery in 3 0 Sec onds or L es s

H ac k 9 . P os t P hotos to Your Blog


Hacks 1-9
Sharing photos has been a popular ac tivity s inc e the invention of
the portable c amera. M os t of us regularly pore over photos
during gatherings with friends and family, whether flipping
through a s tac k of photos , looking through albums , or enduring
projec ted s lides hows c hronic ling every detail of a rec ent
vac ation. Flic kr helps you s hare photos in many s imilar ways
[Hack #1], and it gives you c ontrol over who s ees whic h photos
[Hack #2].

N ow, ins tead of waiting for a gathering to s hare your photos , you
c an make them available to your friends and family almos t as
s oon as you take them [Hack #6]. You c an even add the photos
to your own web s ite [Hack #9] if you want. A nd in addition to
friends and family, Flic kr c an c onnec t your photos with a wider
audienc e of people who might be interes ted in them. Sharing
photos is nothing new, but Flic kr gives you the opportunity to
s hare your photos in new ways .

To get s tarted s haring photos with Flic kr, you jus t need a minute
or two to c reate your ac c ount. Brows e to Flic kr
(http://www.flic kr.c om), and c lic k the "Sign up now! " button
s hown in Figure 1 - 1 .

Figure 1-1. The Flickr front page


Flic kr is owned by Yahoo! , and if you already have a Yahoo!
ac c ount, you c an us e your Yahoo! I D and pas s word to c reate a
new Flic kr ac c ount. I f you don't have a Yahoo! I D yet, c lic king
the "Sign up now! " link will walk you through the ac c ount
c reation proc es s . T he whole proc es s takes les s than a few
minutes , and onc e your Flic kr ac c ount is c reated, you c an s tart
s haring photos .

When you return to Flic kr in the future, you c an c lic k the "Sign
in" link at the top of the Flic kr front page. From there, you'll s ee
the two s ign- in options s hown in Figure 1 - 2 .

Figure 1-2. Flickr sign-in page


I f you c reated your Flic kr ac c ount after A ugus t 1 5 , 2 0 0 5 , you'll
us e the Yahoo! option for s igning in. O therwis e, you c an c hoos e
the Flic kr option on the right. M os t likely, Flic kr ac c ounts
c reated before A ugus t 1 5 , 2 0 0 5 will eventually be moved to
s tandard Yahoo! ac c ounts , but at the time of this writing, the
s ign- in page is a vis ual reminder that Flic kr is a new addition to
the Yahoo! family of applic ations .

T his c hapter will s how you the bas ic s of us ing Flic kr to s hare
photos , and it will take you beyond the upload form [Hack #5] s o
you c an be s haring photos like a Flic kr power us er in no time.
Hack 1. Store, Sort, and Share Your
Photos

To get started with Flickr, you need to understand its basic


f eatures.

A t its mos t bas ic , Flic kr is a web applic ation that helps you
c reate a public journal of photos . You c an upload your photos to
Flic kr and s ee them appear on a web page, with the mos t
rec ently added photo on top. But onc e you s tart playing with
Flic kr, you'll quic kly find that it's muc h more s ophis tic ated. I n
fac t, Flic kr is an open platform for s toring, arranging, s haring,
dis c us s ing, and dis c overing photos with people ac ros s the
globe.

What began as an independent projec t by a s mall c ompany


c alled L udic orp was quic kly s napped up by Yahoo! and is now
reac hing a muc h wider audienc e. I f you don't already have a
Yahoo! ac c ount, you c an s ign up for one via the Flic kr home
page.

A bas ic Flic kr ac c ount is free and lets you


upload up to 2 0 M B of photos per month,
s how up to 2 0 0 of your photos , and c reate
three individual galleries (whic h Flic kr
c alls s ets ). You c an als o upgrade to a paid
Flic kr P ro ac c ount, whic h gives you muc h
more s torage and unlimited s ets . A t the
time of this writing, a Flic kr P ro ac c ount
c os ts $ 2 4 .9 5 per year.

O nc e you've c reated an ac c ount, you c an add s ome information


about yours elf to your profile that will tell others a bit about you.
Flic kr is a s oc ial applic ation, and unlike s ome s ites where
uploading photos feels like a lonely proc es s , adding photos to
Flic kr feels like a group ac tivity.

Store

T he firs t s tep in getting to know Flic kr is uploading s ome of your


photos . T he s teps required to move photos from your c amera to
your c omputer vary widely, s o that will have to be an exerc is e for
the reader. But onc e the photos are on your c omputer, there are
s everal ways to add them to Flic kr.

From your browser

When you're getting s tarted, the s imples t way to upload photos


is via your web brows er and the "U pload photos to Flic kr" page
(http://www.flic kr.c om/photos /upload/). C lic k Brows e... next to
one of the blank fields on the page, and a new window will let you
c hoos e an image file on your loc al c omputer. Figure 1 - 3 s hows
what c hoos ing a file looks like on Windows XP.

Figure 1-3. Choosing photos to upload to Flickr


When you highlight a photo and c lic k O pen, the previous ly blank
field will be filled with the loc al path to the image file. You c an
upload up to s ix photos at a time and s et tags and privac y
s ettings for eac h photo in the group. C lic king U pload s ends your
photos to Flic kr, whic h might take s ome time, depending on the
s ize of your photos and your c onnec tion s peed. O nc e your
photos have been uploaded, you'll have the option to add titles
and des c riptions to eac h of them. I t's eas y to add titles and
des c riptions later as well.

You c an s et default privac y options [Hack #2] for every photo


you upload by c lic king Your A c c ount at the top of any Flic kr page
and c hoos ing D efault P hoto P rivac y from the menu. O r you c an
brows e direc tly to http://www.flic kr.c om/profile_photoc onf.gne to
s et options s uc h as who c an s ee your photos , who c an c omment,
and who c an add notes and tags .

From your desktop

O nc e you're c ompletely hooked on Flic kr, you might want to


upload entire s ets of photographs at a time. You c an find a
number of ways to upload photos on the Tools page
(http://www.flic kr.c om/tools /). T he tools are programs you c an
download and ins tall on Windows or M ac intos h c omputers that
allow you to upload a number of photos at onc e.

Figure 1 - 4 s hows the Windows Flic kr U ploadr in ac tion; you c an


s imply drag images from the file explorer and drop them onto the
Flic kr U ploadr window.

Figure 1-4. Adding photos from the desktop with


Flickr Uploadr
O nc e you've added all of the photos you want to s end to Flic kr
into the Flic kr U ploadr, c lic k the U pload... button. You'll als o
have the option to add tags to the photos or c hange the default
privac y s ettings for thos e photos . T here are many uploading
tools available [Hack #5], s o be s ure to take a look at your
options to s ee whic h tool might work bes t with your s ys tem.

From an email address

I n addition to uploading photos via the Web or a des ktop


applic ation, you c an s end photos to Flic kr by email. C lic k the
Your A c c ount link at the top of any Flic kr page, and c hoos e
"U ploading by email" under the P hoto Settings heading. You c an
als o brows e direc tly to
http://www.flic kr.c om/profile_mailc onf.gne.

O nc e there, you'll find a randomly generated email addres s


that's unique to your Flic kr ac c ount. You c an us e the addres s to
s end photos to Flic kr as an email attac hment. T his option is
partic ularly handy for c ell phone c ameras , bec aus e you c an s nap
your photo on the go and pos t it direc tly to Flic kr [Hack #6],
without making a trip to your home c omputer.

Sort

You'll find every photo you upload in your Flic kr photos tream. A
photos tream is s imply a lis t of every photo you've uploaded in
revers e- c hronologic al order, with the lates t photo you've
uploaded firs t. O nc e your photos are in your photos tream,
however, there are a number of ways you c an organize them
beyond the c hronologic al lis ting.
Tagging

Tagging is a s imple form of organization that lets you as s oc iate


keywords with eac h of your photos . U nlike traditional
c ategorization s c hemes , tags are freeform, and you c an us e any
words , numbers , or phras es you like. Figure 1 - 5 s hows a photo
at Flic kr, with its tags lis ted jus t to its right. T he photo was taken
in the town of Kaneohe, H awaii, at a Buddhis t temple, and the
photographer has tagged the photo with the words temple,
Kaneohe, and Hawaii.

Figure 1-5. A photo with tags at Flickr


C lic king on any tag will s how you all of the photos that you've
tagged with that word. C lic king the globe ic on next to any tag will
s how you photos by everyone at Flic kr tagged with that word.
Tagging photos is a fairly s imple proc es s , but learning a few
tagging hints [Hack #10] c an help you determine whic h
keywords to us e.

Organizing

T he key to more c omplex organization is the Flic kr tool c alled


Organizr . O rganizr runs in your brows er, and you'll need to have
the free M ac romedia Flas h P layer
(http://www.mac romedia.c om/go/getflas hplayer/) ins talled to
us e it. You c an fire up O rganizr by c lic king the O rganize link at
the top of any Flic kr page.

You'll find your photos in O rganizr's main window. You c an view


all photos ; limit your photos by date; or s earc h your titles ,
des c riptions , and tags . T he s liders below the main window adjus t
the dates you'd like to view, as s hown in Figure 1 - 6 .

Figure 1-6. Sorting photos with Flickr Organizr


I ns ide O rganizr, you c an c reate and edit photo s ets . A s et is
group of photos that you as s emble into an individual gallery.
O nc e you've c reated a s et and given it a title, you c an drag a
photo from the main window and drop it into a s et on the right to
add the photo to that s et. From there, you c an arrange the
photos in a s et into a s pec ific order. Figure 1 - 7 s hows what the
c over page of a s et looks like to s omeone brows ing the s et for
the firs t time.

Figure 1-7. A Flickr set


Free Flic kr ac c ounts are limited to three
s ets , but you c an c reate an unlimited
number of s ets with a Flic kr P ro ac c ount.

T he "V iew as s lides how" link on the front page of a s et will let
people s ee the group of photos as a Flas h pres entation. V iewers
don't even have to pres s keys or c lic k mous e buttons ; they c an
s it bac k and watc h the photos dis s olve in and out as the
pres entation automatic ally moves from one pic ture to the next.

Share

O ne of the primary benefits of us ing Flic kr is that onc e your


photos are uploaded, they are ac c es s ible to anyone with a web
brows er.

Free to the public

T he eas ies t way to s hare all of your photos is to c reate a s imple


U RL , c alled a Flickr addres s , that you c an s hare with others .
Brows e to http://www.flic kr.c om/profile_url.gne, and c hoos e a
s imple word as your addres s . T he format of the U RL will look like
this :
http://www.flickr.com/photos/insert your word/

I t's important to c hoos e your Flic kr addres s c arefully, bec aus e


your c hoic e is permanent; you c an't edit your Flic kr addres s
onc e you've c reated it. T he newly c reated U RL will point direc tly
to your photos tream, and you c an give the U RL to your friends
and family or link to your photos tream from another web s ite
us ing the U RL .

O nc e your photos are on Flic kr, you c an als o s hare them by


automatic ally pos ting them to a weblog [Hack #9], or by
dis playing your lates t photos with a Flic kr badge [Hack #7].
Flic kr als o provides RSS feeds for photos treams , groups , and
tags , s o onc e your photos are in the s ys tem, there are myriad
ways for others to view them.

O ne benefit of thes e methods of s haring is that others viewing


your photos don't need to be members of Flic kr to s ee them;
they don't have to go through the ac c ount c reation proc es s
s imply to look at your photos . H owever, if they do go the extra
mile and bec ome Flic kr members thems elves , you'll have
s everal more ways to c onnec t and s hare photographs .

Flickr community

Flic kr works bes t when your friends and family are als o
partic ipating at the s ite. You c an add anyone with a Flic kr
ac c ount as a friend, family member, or c ontac t.
Keep in mind that the c ategory another
Flic kr member is in will determine whic h
photos of yours that pers on c an s ee if you
alter your photos ' default privac y s ettings .

A s you build a group of c ontac ts [Hack #24] at Flic kr, you'll be


able to eas ily brows e their photos , jus t as they c an brows e
yours . C lic king the Your C ontac ts ' link at the top of any Flic kr
page will s how the lates t photos added by all of your c ontac ts ,
and it's a great way to keep up with your friends .

You c an als o brows e a full lis t of your c ontac ts by c lic king the
P eople link at the top of any page; c lic king a name will take you
to that pers on's photos tream. Figure 1 - 8 s hows a c ontac t lis t at
Flic kr.

Figure 1-8. A list of contacts at Flickr


T he G roups feature lets anyone form a public dis c us s ion and
photo s haring s pac e at Flic kr. I n addition to s ending photos to a
group photo pool, you c an pos t mes s ages to the group and c arry
on c onvers ations . For example, there's a group c alled T he
Books helf P rojec t, available at
http://www.flic kr.c om/groups /books helf/, whos e members s hare
photos of their home books helves and dis c us s the topic of
s toring books .

I f you're interes ted in a s pec ific topic , c hanc es are good that
s omeone has c reated a s pec ific Flic kr group devoted to it. You
c an brows e a full lis t of groups , organized by topic , at
http://www.flic kr.c om/groups _brows e.gne. Figure 1 - 9 s hows the
Flic kr group for Yahoo! Hacks (my previous book for O 'Reilly),
whic h you'll find online at
http://www.flic kr.c om/groups /yahoohac ks /.

Figure 1-9. A Flickr group page


Beyond c ontac ts and groups , Flic kr members c an c omment on
eac h other's photos , help out with tagging, and even add notes
to s pec ific areas of a photo. (A s always , thes e features are
c ontingent on the permis s ions you s et for your photos [Hack
#2].)
Hack 2. Control Who Sees Your Photos

Flickr has a f lexible privacy system that enables you to share


photos with your f riends, your f amily, or the worldor keep them
to yourself .

Flic kr exis ts s o that you c an s hare photos , but you might not
want everyone in the world to s ee all of your photos . Your friends
would love to s ee photos of you knoc king bac k a few beers at
your favorite bar, but your bos s might frown on them. Your family
would love to s ee photos of you dres s ed up for your c ous in's
wedding, but your friends might not apprec iate your powder- blue
tuxedo. With a bit of planning, you c an make s ure that your Flic kr
photos are s hared with only the people whom you want to s ee
them (or not s hared at all).

E very photo s ent to Flic kr has a privac y s etting, and the default
s etting is P ublic . When a photo is P ublic , anyone vis iting Flic kr
c an s ee the photo. I f you want to c ontrol ac c es s to your photos
more c los ely, you c an s et them as P rivate. But the term
"P rivate" is a bit mis leading, bec aus e there are different levels
of privac y. To unders tand how the levels of privac y work, you
need to know a bit about how Flic kr c ontac ts work.

Flickr Contacts

When you mark a photo as P rivate, the ability to view the photo
is limited to you (of c ours e) and c ertain people among your
Flic kr c ontac ts . Say you want to s hare a s lightly embarras s ing
baby pic ture of yours elf with members of your family, but not the
res t of the world. Firs t, you'll need to add your family members to
your c ontac t lis t by inviting them to join Flic kr (or, if they already
have ac c ounts , brows ing to their photos tream pages and adding
them as c ontac ts ).

To invite people, brows e to your Flic kr home page and c lic k the
I nvite link at the top of the page. E nter your family members '
email addres s es and names , and des ignate their relation to you
by c hec king the box next to "T his pers on is family." C lic k Send,
and Flic kr will s end out invitations . O nc e a family member
rec eives the invitation, s he c an regis ter at Flic kr, and s he'll be
added to your c ontac t lis t as a family member.

Flic kr c ontac ts c an have three different s tatus es : Family,


Friends , or C ontac t. O nc e s omeone on your c ontac t lis t is
des ignated as Family, he'll have the ability to view photos that
you've des ignated at P rivate, V is ible to Family. You c an als o
des ignate photos as P rivate, V is ible to Friends or P rivate,
V is ible to Friends and Family to limit ac c es s to jus t friends , or
jus t friends and family members . C ontac ts without a Friends or
Family des ignation will be able to s ee your P ublic photos only.

You c an c hange a c ontac t's s tatus at any time by c lic king the
P eople link at the top of any Flic kr page. From there, navigate
through your c ontac ts and hover over the ic on of the c ontac t
you'd like to c hange. A pink box like the one in Figure 1 - 1 0 will
appear, as king if you'd like to c hange the s tatus of your c ontac t.

Figure 1-10. The change contact question box


C lic k the box, and you'll s ee a c hange c ontac t s tatus dialog like
the one s hown in Figure 1 - 1 1 .

Figure 1-11. The change contact dialog


A djus t the s ettings and c lic k O K, and the c ontac t will have the
ability to s ee photos (or not), depending on his s tatus .

Setting Privacy

You c an s et the privac y s ettings for s pec ific photos at any point,
but it's bes t to do s o when you initially upload the photos to
Flic kr. Figure 1 - 1 2 s hows the privac y s ettings on the bas ic
upload form.

Figure 1-12. The privacy settings on the image


upload form
E ven if you're us ing a des ktop uploading tool [Hack #5], you'll
find that they all offer a way to s et the privac y level for the batc h
of photos you're uploading.

Be aware that if you add a photo to a Flic kr


group pool, any member of the group will
be able to s ee that photo, regardles s of its
privac y s etting.

You c an always s ee how a photo is marked in Flic kr by c hec king


the s ettings underneath the photo. Brows e to your photos tream
and look for a s quare ic on direc tly underneath the photo. T he
c olor of the ic on indic ates its privac y s tatus . G reen means the
photo is P ublic , yellow means the photo is P rivate but friends or
family members c an view it, and red means you're the only us er
that c an view the photo. You'll als o find a phras e next to the ic on
that indic ates who c an s ee the photo, as s hown in Figure 1 - 1 3 .

Figure 1-13. Private photos on Flickr


You c an c lic k the "s et privac y" link at any time to c hange the
privac y of a photo.

To publis h a photo to your weblog with the


Blog T his feature at Flic kr, the photo will
need to be marked as P ublic . I f you
publis h a P ublic photo and then c hange its
s tatus later, the photo will s till be vis ible
on your weblog, but people c lic king
through to the photo at Flic kr will not be
able to s ee the photo detail page.

I f you find that you're marking every photo you upload to Flic kr
as P rivate, you c an s et this as the default privac y s etting. A t the
bottom of any Flic kr page, under the Your A c c ount heading, c lic k
the P hoto P rivac y link to s et your privac y preferenc es , as s hown
in Figure 1 - 1 4 .

Figure 1-14. Global privacy settings


A s you c an s ee, you c an s et a default privac y value for your
photos , and you c an s et the level of partic ipation you'd like other
Flic kr us ers to have with your photos .
Hack 3. Manage Image Metadata

Flickr will display the inf ormation that most digital cameras
embed inside a photo, and with the right tools, you can control
this data.

I f you take photos with a digital c amera, c hanc es are good that
the original files that c ome from the c amera c ontain information
about the c amera s ettings when you s napped the photos . T his
information c an inc lude the date and time, how long the s hutter
was open, the s ettings you c hos e for the s hot, and whether your
lens was zoomed in or out. T his type of information is c alled
metadata, whic h literally means data about data.

I n the days before digital c ameras , one of the bes t ways to s tore
information about a photo was by flipping over a print and
phys ic ally writing on it. I n the digital world, information about a
photo c an be embedded within the image file its elf. V iewing the
info c an help you remember how you got a great s hot, or tell
others how they c an ac hieve a s imilar effec t.

I f metadata is pres ent in your photo when you upload it to Flic kr,
you'll find your c amera make and model along with a "M ore
properties " link on the photo detail page, as s hown in Figure 1 -
15.

Figure 1-15. The "More properties" link on a


photo detail page
C lic king the "M ore properties " link takes you to a page like the
one in Figure 1 - 1 6 , with many more details about the
photograph.
Figure 1-16. "More properties" page on Flickr
A s you c an s ee, Flic kr has c hos en to highlight c ertain properties
and inc lude others in a grey box. A ll of this data that Flic kr c an
dis play c omes from a few different s ourc es , and it helps to be
familiar with s ome of the terms before you s tart editing and
refining your photo metadata. T he exac t metadata will differ by
c amera and s oftware, but here's a look at s ome c ommon
metadata properties you'll find:

Camera

T his property s hows the manufac turer and model of


c amera that was us ed to take the photograph.

Expos ure

T his is the length of time in s ec onds that the s hutter


was open on the c amera.

Aperture

T he aperture c ontrols light c oming into a c amera, and


this property s hows the aperture s etting in its s tandard
f- s top meas urement.

Focal Length

T his property s hows the foc al length (in millimeters )


when the photo was taken. I f the c amera has a fixed
lens , this will be a fixed value. A zoom lens will s how
differenc es between s hots as the lens is zoomed in and
out.

I SO Speed

M any digital c ameras allow adjus tments for light


s ens itivity, and this property s hows the I SO s peed s et
on the c amera when the photo was taken.

Expos ure Bias

I f the photographer s et the c amera to under- or


overexpos e a photograph, this property will s how how far
the s etting was pus hed in either direc tion.

Orientation

I f available, this property s hows how the c amera was


pos itioned when the photo was taken.

Software

I mage- produc tion s oftware s uc h as P hotos hop us ually


embeds its s tamp on any metadata, letting others know
the s oftware us ed to produc e the image.
Dates and Times

Several dates and times c an be embedded in a photo,


inc luding when the photo was taken, when the photo was
opened in produc tion s oftware, and when the photo was
las t modified.

Expos ure Mode

T his property c an let you know what type of expos ure


mode the c amera was in when the photo was taken,
inc luding automatic , manual, or aperture priority.

Artis t Name

T his property c an be s et to the name of the


photographer.

Copyright

P hotographers c an add s pec ific c opyright information to


a file, and that info is s hown in this property.

Keywords , Title, and Des cription

M uc h like titles , des c riptions , and tags at Flic kr, thes e


properties , embedded as metadata by the photographer,
c an help identify the s ubjec t of the photo.

T he mos t c ommon metadata format is c alled E Xc hangeable


I mage File (E XI F) data, and it c ontains mos t of the c amera
s ettings . I n addition, s ome c ameras and programs embed
metadata in the I nternational P res s Telec ommunic ations
C ounc il (I P T C ) format, whic h inc ludes detailed artis t
information, and the more rec ent XM L- bas ed eXtens ible
M etadata P latform (XM P ) format endors ed by A dobe. You'll s ee
thes e ac ronyms us ed quite a bit (and often interc hangeably) in
different image s oftware programs ; jus t be aware that when you
s ee them, you're dealing with image metadata.

You c an us e Flic kr and your digital c amera without ever knowing


that image metadata exis ts , and you won't be mis s ing muc h. But
if you're interes ted in the c raft of photography and want to s ee
the tec hnic al details behind your favorite photos , this metadata
c an be a great learning tool. A nd, in turn, you c an s hare your
tec hnic al details with others s o they c an learn from your photos .

Viewing Metadata

T he firs t s tep to unders tanding image metadata is s imply to take


a look at the data embedded in your photographs . H ere are a few
image tools that c an both read and edit metadata in your
images .

Photoshop CS

O pen a photo in P hotos hop and c hoos e File File I nfo... from
the menu to dis play the metadata window s hown in Figure 1 - 1 7 .
Figure 1-17. Viewing camera metadata in
Photoshop CS
C hoos e a page of data on the left, and you'll s ee the details on
the right. T he C amera D ata 1 and 2 pages s how the tec hnic al
info about the photo embedded in the file. You c an't edit this
information within P hotos hop, but you c an view the info s o you'll
know what others will s ee onc e you've added the image to Flic kr.

I f you c lic k the D es c ription page, though, you have the option to
add a title, author, des c ription, keywords , and c opyright
information to the image metadata. Figure 1 - 1 8 s hows the
metadata entry form.

Figure 1-18. Adding a title and description and


other metadata to an image file with Photoshop
O nc e you've added the data, c lic k O K. Bac k in the main
P hotos hop window, s ave the image to be s ure the metadata is
added. I t's always a good idea to us e the File Save A s ...
feature to make a c opy of the file; that way, no matter what
c hanges you make to the image metadata, you'll always have
the original file with the original metadata intac t.

I n addition to the File I nfo metadata window, you c an edit


metadata within P hotos hop from the File Brows er. C hoos e File
Brows e from the menu and navigate to a folder with images .
H ighlight an image on the right, and open the metadata palette in
the lower- left c orner of the brows er. Fields that you c an edit are
noted with a penc il, as s hown in Figure 1 - 1 9 .

Figure 1-19. Photoshop File Browser metadata


palette
U s ing the File Brows er is a quic k way to add titles and
des c riptions to photos before you upload them to Flic kr. Flic kr
will automatic ally extrac t the title, des c ription, and keyword
information from the image file if it exis ts in the image metadata.

Exifer

E xifer (http://www.friedemann-
s c hmidt.c om/s oftware/exifer/index.htm) is a free program
s pec ific ally des igned to read and edit image metadata. O nc e you
open E xifer, brows e to a folder with images and highlight a
s pec ific image to s ee the metadata in the right pane, as s hown in
Figure 1 - 2 0 .

Figure 1-20. Viewing metadata with Exifer


D ata that you c an edit in E xifer is noted with the paper- and-
penc il ic on. D ouble- c lic k an editable field to c hange the value.
U nlike P hotos hop, E xifer will let you adjus t the time an image
was taken; this is es pec ially handy for c orrec ting the times tamp
s et by a c amera with the wrong time s etting, or if you took
photos in a different time zone without adjus ting the s etting.

Flic kr does not s et the date and time the


photo was taken bas ed on the E XI F data.
I f you upload a photo that was taken years
ago, you'll have to update the "taken on"
date by hand, even if the E XI F data is
ac c urate.

E xifer will give you the option to s ave the original metadata in a
s eparate file. You may want to do this , bec aus e there's no Save
A s ... option in E xifer, and any metadata c hanges are written into
the file.

jhead

A nother free program that c an read and write s ome image


metadata is jhead (http://www.s entex.net/~mwandel/jhead/).
jhead is a c ommand- line program, s o onc e you've downloaded
the vers ion for your operating s ys tem, you'll need to open up a
c ommand prompt to us e it.

O n Windows , you c an find the c ommand prompt at Start


P rograms A c c es s ories C ommand P rompt. M ac us ers
c an s imply open the Terminal app.

From the c ommand prompt, c all the program and inc lude an
image file to analyze, like s o:

jhead moon.jpg

T he output will inc lude c ommon E XI F data, like this :

File name : moon.jpg


File size : 38366 bytes
File date : 2005:09:14 15:07:28
Camera make : Canon
Camera model : Canon EOS DIGITAL REBEL
Date/Time : 2004-08-27T22:35:05
Resolution : 510 x 343
Flash used : No
Focal length : 300.0mm (35mm equivalent: 2871mm)
CCD width : 3.76mm
Exposure time: 0.0080 s (1/125)
Aperture : f/16.0
ISO equiv. : 200
Jpeg process : Progressive

You have a number of options for c hanging the metadata with


jhead. You c an adjus t for time- zone problems by moving the time
forward or bac kward. U s e the -ts s witc h to c hange the date and
time of a photograph, like this :

jhead -ts2003:08:27-22:35:05 moon.jpg

E ven though the c amera noted that the photo was taken in
2 0 0 4 , editing the metadata will tell Flic kr and the world that the
photo was really taken in 2 0 0 3 . To s ee all of the metadata
editing options in jhead, bring up the help doc umentation, like
this :

jhead -h

While not as friendly as the other programs , you might find jhead
us eful for editing the image metadata of entire folders of photos
at a time.

Hiding Metadata

I f you'd rather not s hare your image metadata with the world,
there are s ome s teps you c an take to keep the info to yours elf.
Firs t, Flic kr provides a way to turn of the "M ore properties " link
on your photo detail pages .

To hide this link, brows e to Flic kr and c hoos e the P rofile P rivac y
link under Your A c c ount at the bottom of the page. C hec k the
box next to "H ide my E XI F data? " and c lic k Save C hanges . Keep
in mind, though, that while the E XI F properties page will be
hidden from other Flic kr us ers , a determined us er will s till be
able to download the original file and extrac t the metadata.
Removing metadata from image files will
reduc e the file s ize by 5 to 1 0 kilobytes ,
s o if you're really trying to s queeze every
extra byte from your photos , removing
E XI F data will help. You won't notic e a
differenc e in upload times or Flic kr
bandwidth us age with a c hange that s mall,
though many programs (inc luding
P hotos hop) remove the data if you us e the
"Save for Web" option.

To remove image metadata c ompletely, you c an us e any of the


programs mentioned for editing image metadata. I n P hotos hop,
open the File I nfo window and c lic k A dvanc ed on the left.
H ighlight E XI F P roperties on the right and c lic k D elete. D o the
s ame for any other metadata you'd like to delete, and then be
s ure to s ave a c opy of the file. With E xifer, c lic k E XI F/I P T C
Remove from the menu, and with j head, us e the -de s witc h. For
example, the following c ommand would remove all of the image
metadata from a file c alled moon.j pg:

jhead -de moon.jpg

T he c hoic e to us e metadata and s hare it with others is up to you,


but be aware that even if you do nothing, s ome of your data
might be available ins ide your photographs .
Hack 4. Resize Photos for Flickr

Images coming directly f rom a digital camera or scanner are


of ten quite large. Resizing them bef ore sharing them can save
your Flickr bandwidth.

D igital photos c ome in all s hapes and s izes , bec aus e they're
taken by devic es with varying c apabilities and us ed for a number
of different purpos es . I f you're going to print a digital photo, you
want the highes t res olution pos s iblethe more pixels there are in
a photo, the better the print quality will be when trans lating that
photo to paper. I f you're jus t going to dis play an image on a
c omputer s c reen, on the other hand, you c an us e a s maller
image, bec aus e the s c reen does n't need as many pixels to
dis play a s harp image. Bec aus e Flic kr images are primarily us ed
for dis play on c omputer s c reens , you c an take advantage of that
fac t and tailor your images jus t for Flic kr by res izing them.

Why Size Matters

When you're us ing Flic kr, you don't need to think about the s ize
of an image. H owever, there are s everal reas ons why you s hould
keep image s ize in mind. P os s ibly the mos t important reas on is
c ons erving bandwidth. T he free vers ion of Flic kr allows 2 0
megabytes of trans fer eac h month, and larger image dimens ions
us ually mean a larger file (in megabytes ) to upload. I t takes
longer to upload larger photos , and you c an upload fewer photos
per month at the large s ize.

I f you don't pay attention to your bandwidth you might not ever
know you're uploading extremely large images , bec aus e Flic kr
automatic ally res izes them to a number of different s tandard
s izes . For example, all photos in your photos tream will be
dis played at a maximum of 2 4 0 pixels wide (or high, depending
on their orientation), allowing people to view many of your photos
at onc e. E ac h image is dis played at a maximum of 5 0 0 pixels at
the longes t dimens ion on its detail page, s o that viewers c an s ee
a bit more detail than was available in the photos tream lis ting.
I n fac t, if you upload a photo that's 1 ,0 0 0 pixels wide, no
viewers will s ee it at its full s ize unles s they c lic k the A ll Sizes
button on the photo detail page.

T his means that 5 0 0 pixels is as wide or tall as an image ever


needs to be for normal brows ing at Flic kr. I f you c ut that 1 ,0 0 0 -
pixel image in half, you'll s ave s ome time uploading, and you'll
s ave your Flic kr bandwidth for more images .

A nother reas on for res izing your images is that you might not
want other Flic kr us ers to have ac c es s to larger vers ions of your
photographs . L arge (high- res olution) vers ions of photos not only
s how more detail on the s c reen, but are als o better for printing.
So, if you'd rather not give other Flic kr members print- quality
vers ions of your photos , res izing them before you upload will
make s ure that people have ac c es s only to vers ions that look
good on a c omputer s c reen. T his will allow you, for example, to
give everyone ac c es s to s c reen- quality vers ions of your photos ,
but c harge for print- quality vers ions at your own web s ite.

Programs to Resize Photos

To res ize an image, you'll need a program that c an handle the


tas k, and there are probably s everal hundred available. T his
hac k s hows how to res ize images with five different programs .
You might have one of thes e programs ins talled on your
c omputer already; if not, you'll probably want to ac quire one of
thes e or any of the numerous other offerings .

Photoshop CS

A dobe P hotos hop (http://www.adobe.c om/photos hop/) is the


s tandard for image profes s ionals , and it's available for both
M ac s and P C s . A t $ 5 9 9 (at the time of this writing) it's not
c heap, but P hotos hop will give you a full- featured digital photo
lab that lets you adjus t images in many different ways , inc luding
res izing them. A dobe als o offers a light, les s - fully- featured
vers ion of P hotos hop c alled P hotos hop E lements for $ 9 9 .

O pen the image you want to res ize in P hotos hop and c hoos e
I mage I mage Size from the top menu to bring up the I mage
Size dialog. (O r, in P hotos hop E lements , c hoos e I mage
Res ize I mage Size.) C hange the units to pixels in the top
drop- down menu, and enter your des ired width, as s hown in
Figure 1 - 2 1 .

Figure 1-21. Resizing a large image with


Photoshop CS
P hotos hop will automatic ally c alc ulate the proper height in
pixels . (I f your image is oriented vertic ally, c hange the height
ins tead and P hotos hop will c alc ulate the proper width.) A t the
top of the P ixel D imens ions s ec tion of the I mage Size dialog,
you'll s ee an es timate of the new file s ize. I n Figure 1 - 2 1 ,
res izing the image reduc es the photo of a flower from 1 8
megabytes to les s than 1 megabyte. U ploading this photo will
now us e up only a frac tion of your bandwidth, ins tead of
c ons uming prac tic ally your entire month's alloc ation.

With the new width and height s et, c lic k O K to res ize your image.
C hoos e File Save A s ... from the menu, and give your newly
res ized image a new name that you'll rec ognize. (I t's always a
good idea to keep a c opy of your original photo, rather than
overwriting it, s o you c an go bac k and print the file or us e it for
s ome other reas on down the road.)

Paint Shop Pro X

P aint Shop P ro X (http://www.c orel.c om/paints hoppro/) is an


alternative to P hotos hop offered by C orel for $ 1 2 9 . You c an
bring up the Res ize dialog, s hown in Figure 1 - 2 2 , by c hoos ing
I mage Res ize from the menu or us ing the keyboard
s hortc ut Shift- S.

Figure 1-22. Resizing an image with Paint Shop


Pro X
E nter a new width or height, and P aint Shop P ro will
automatic ally c alc ulate the other dimens ion. C lic k O K and s ave
the new file under a new name, pres erving the original.

IrfanView 3.97

I rfanV iew (http://www.irfanview.c om) is a lightweight image-


editing tool that's free for nonc ommerc ial us e. To bring up its
"Res ize/Res ample image" dialog, pres s C trl- R or c hoos e I mage
Res ize/Res ample from the menu. E nter the new s ize, as
s hown in Figure 1 - 2 3 .

Figure 1-23. Resizing an image with IrfanView


You c an als o c hoos e an alternate s ize from the "s tandard
dimens ions " lis t on the right s ide of the window. O nc e you've
entered the new s ize, c lic k O K, and then s ave the file as a new
image.

Windows XP Image Resizer PowerToy

M ic ros oft offers a s eries of s mall, free applic ations that you c an
add to Windows XP, c alled "P owerToys ." E ac h P owerToy
performs s ome s pec ific tas k that's not inc luded with the bas ic
operating s ys tem ins tallation, and the I mage Res izer P owerToy
does jus t what you'd expec t. To get a c opy, brows e to
http://www.mic ros oft.c om/windows xp/downloads /powertoys /xppow
and s earc h for "image res izer" on the right s ide of the page.

O nc e the P owerToy is ins talled, you c an res ize any image by


right- c lic king the image file and c hoos ing Res ize P ic tures from
the menu. You c an als o res ize a whole batc h of images at onc e
with this program, and it's a quic k way to res ize an entire folder
of images .

When you c lic k Res ize P ic tures , you'll s ee a window like the one
s hown in Figure 1 - 2 4 .

Figure 1-24. The options available in the Image


Resizer PowerToy
You c an c hoos e a s ize from the options available, or c lic k
C us tom and enter your own s ize. U nfortunately, the I mage
Res izer won't automatic ally c alc ulate the c orres ponding height
or width, s o you'll need to do s ome math on your own if you go
with a c us tom s ize.

O nc e you've made your c hoic e, be s ure that the "Res ize the
original pic tures " option is not c hec ked, and c lic k O K. T he
I mage Res izer will c reate new images with the s ame names , but
you'll find the words Small, M edium, L arge, WinC E , or C us tom
added to the new filenames . For example, a file c alled
s unflower.j pg would be c opied, res ized, and s aved as s unflower
(s mall).j pg if you c hos e the s mall image s ize from the menu.

iPhoto

M ac O S X us ers c an rely on iP hoto, an image- organizing


program that is inc luded with O S X by default. To res ize photos
in iP hoto, s imply s elec t the photos you'd like to res ize and
c hoos e Share E xport... from the menu. C hoos e the File
E xport tab and s et your maximum width or height in the "Sc ale
images no larger than" boxes s hown in Figure 1 - 2 5 .

Figure 1-25. Resizing images in iPhoto


Be s ure to c hange the format to J P G in the drop- down menu, and
make s ure the "U s e extens ion" option is c hec ked. C lic k E xport
and c hoos e a memorable loc ation for your res ized photos .

Thinking Small

You c an now upload your newly res ized images to Flic kr, us ing
your favorite method [Hack #5]. You s hould notic e that it takes
les s time to trans fer the files , and you'll have more room in your
Flic kr ac c ount to upload files .

A ls o note that many Flic kr upload tools will automatic ally res ize
photos for you, s o be s ure to c hec k the options available to you
in your uploading tool of c hoic e.

T he tools dis c us s ed here are jus t a few of


the available image programs that you c an
us e to res ize your photographs . A quic k
s earc h for "image res izing program" on
G oogle will return dozens and dozens of
potential c andidates .
Hack 5. Add Photos Quickly

Flickr uploading tools can speed up the process of adding photos


to Flickr.

A dding a photo to Flic kr is n't hard. I f you brows e to Flic kr, log in,
and c hoos e U pload from the menu, you'll find the upload page
[Hack #1], with s ix empty fields waiting for photos . C lic k the
Brows e... buttons next to the fields and c hoos e s ome loc al files ,
and your photos will s oon make their way from your des ktop to
Flic kr.

I f you want to add more than s ix photos at a time, though, the


upload page begins to look like an awfully s low way of
trans ferring files . You have to upload in batc hes of s ix, and wait
for eac h group to trans fer before s tarting the next group.
U ploading 3 0 photos would require 5 trips to the upload page,
and c ons tant monitoring to find out when the las t batc h of photos
was done trans ferring.

A nother fac tor to c ons ider when uploading


photos is the s ize of the photos
thems elves . A larger image file will take
longer to trans fer, s o you might want to
res ize your photos [Hack #4] before
adding them to Flic kr.
L uc kily, Flic kr has provided s everal tools to make uploading
eas ier. A n uploading tool is s imply a program you c an ins tall on
your c omputer that c ommunic ates with Flic kr. You c an find a lis t
of uploading tools c reated by Flic kr developers at
http://www.flic kr.c om/tools /, along with s ome tools written by
outs ide developers . T his hac k dis c us s es how to us e s ome of the
available Flic kr upload tools .

Granting Your Permission

A ny tool that us es the Flic kr A P I to add photos to your


photos tream needs your explic it permis s ion. A s you ins tall
s oftware that c ommunic ates with Flic kr, you'll likely enc ounter a
Flic kr permis s ions page like the one s hown in Figure 1 - 2 6 .

Figure 1-26. The Flickr permissions page


T his proc es s ens ures that you give ac c es s only to programs
that you're aware of, and you c an view a lis t of the applic ations
you've approved at any time by logging into Flic kr and brows ing
to the A uthentic ation L is t page
(http://www.flic kr.c om/s ervic es /auth/lis t.gne). I f you s ee the
permis s ions page while us ing an upload tool, you'll need to c lic k
the O K, I 'll A llow I t button; otherwis e, the upload tool won't be
able to add your photos to Flic kr.

Batch Uploading Tools

Batc h uploading tools s ave you time by letting you upload entire
groups of photos at onc e. L et's take a look at s ome of the
available options .

Uploadr for Mac

T he offic ial uploading tool for M ac O S X us ers is c alled U ploadr.


D ownload the program from the Flic kr Tools page
(http://www.flic kr.c om/tools /), and double c lic k the .dmg file to
mount it. D rag the Flic kr U ploadr applic ation ic on from the
Flic ker U ploadr window to your des ktop or Applications folder to
ins tall it. O nc e it's ins talled, double- c lic k the U ploadr ic on and
grant your permis s ion to the applic ation. A fter you're logged in,
you c an s tart dragging and dropping photos into the left pane of
the U ploadr, as s hown in Figure 1 - 2 7 .

Figure 1-27. Flickr Uploadr for Mac


You c an s et titles , des c riptions , and tags for eac h individual
photo, or you c an c lic k the Batc h tab to s et global privac y
attributes and tags for the entire group of photos . You c an als o
s et the U ploadr to automatic ally res ize your photos before
s ending them to Flic kr, s aving trans fer time and bandwidth.
C hoos e Flic kr U ploadr P referenc es from the menu to s et
your preferred maximum photo s ize.

O nc e your photo attributes are s et, you c an c lic k U pload to s end


your photos to Flic kr, and they'll be trans ferred in the
bac kground.

FlickrExport for iPhoto

I f you manage your photos with iP hoto on your M ac , you might


want to try the Flic krE xport plug- in written by Fras er Speirs
(http://www.c onnec tedflow.c om/blog/). T he plug- in lets you us e
the iP hoto interfac e to s elec t photos to s end to Flic kr.

D ownload the plug- in from


http://www.c onnec tedflow.c om/flic krexport/, and follow the
ins tallation ins truc tions onc e it's on your des ktop. O nc e the
plug- in is ins talled, open up iP hoto and s elec t a batc h of photos
from your L ibrary. C hoos e Share E xport from the iP hoto
menu, and c lic k the Flic kr button at the top of the page. You'll
s ee the Flic kr E xport dialog s hown in Figure 1 - 2 8 .

Figure 1-28. FlickrExport for iPhoto


A s with U ploadr, you c an s et titles , c aptions , tags , and privac y
s ettings for eac h photo, or you c an us e the "A pply to A ll"
buttons to s et attributes for the entire batc h. O nc e your s ettings
are in plac e, c lic k E xport to s end the photos to Flic kr.

Uploadr for Windows

M ac us ers aren't the only ones who c an benefit from offic ial
Flic kr tools , and there's a vers ion of U ploadr for Windows
available at the Flic kr Tools page (http://www.flic kr.c om/tools /).
Be s ure to c hoos e the proper vers ion of U ploadr for your vers ion
of Windows ; download the program and double- c lic k the ic on to
s tart the ins tallation.

U ploadr for Windows is a bit more s implis tic than its M ac c ous in,
and you won't be able to add titles , c aptions , or tags until you've
trans ferred the photos to Flic kr. To trans fer photos , s imply drag
the images to the U ploadr window, as s hown in Figure 1 - 2 9 , and
c lic k the U pload... button.

Figure 1-29. Flickr Uploadr for Windows


U ploadr will automatic ally res ize your photos if you'd like, and
you c an s et that preferenc e by c lic king the light s witc h ic on in
the main U ploadr window. Figure 1 - 3 0 s hows the Flic kr Settings
window.

Figure 1-30. The Flickr Settings window in


Uploadr for Windows
Windows XP Import Wizard

Windows XP has s ome nic e built- in features for working with


photos , and Flic kr has a tool that extends the publis hing
features to s end photos direc tly to Flic kr. O n the Tools page,
look for a link titled D ownload "Send To Flic kr" Windows XP
E xplorer Wizard, right- c lic k the link, and c hoos e Save A s ... to
s ave the file wizard.reg to your c omputer. D ouble c lic k wizard.reg,
and approve the additions to your Regis try. T his will ins tall the
nec es s ary s ettings to export images to Flic kr.

To try out the wizard, brows e to any folder that c ontains pic tures
with the Windows file explorer. C hoos e "P ublis h this folder to the
Web" to s tart the wizard. I f you don't s ee the P ublis h option,
c hoos e Tools Folder O ptions ... from the menu and make
s ure the "Show c ommon tas ks in folders " option is s elec ted.

A fter you c lic k "P ublis h this folder to the Web," you c an s elec t
the photos from the folder that you want to add to Flic kr. Figure
1 - 3 1 s hows the s elec tion proc es s .

Figure 1-31. Selecting photos to upload with the


Windows XP Import Wizard
O nc e you've made your s elec tions , c lic k N ext and c hoos e Flic kr
from the lis t of options . T he firs t time you run the wizard, you'll
need to grant permis s ion to the program. O nc e you grant
permis s ion, you'll get an authorization c ode to enter into the
wizard. E nter the c ode into the applic ation, c lic k N ext, and you'll
be s et to s end your photos .

You c an't add titles or c aptions to photos before s ending them,


but you c an s et tags and privac y options for the batc h. You als o
have the option of res izing the photos automatic ally before
they're s ent. O nc e your photos are available at Flic kr, you'll
have the option to add titles and des c riptions , and you c an us e
batc h editing [Hack #35] to s peed things up.

Desktop Uploading Widgets

D es ktop uploading widgets are s mall applic ations that run on


your des ktop and trans fer images to Flic kr. T hey won't help you
upload images in large batc hes , but you c an drag and drop a
s ingle photo onto the widget to s end it to Flic kr. T his c an s ave
you the s teps of opening your brows er, finding the upload page,
and brows ing around for the photo you'd like to s end. I ns tead,
you s imply drag the photo onto the widget, drop it, s pec ify your
tags , and c lic k U pload. (U nfortunately, you c an't s pec ify a title
and des c ription while uploadingthe widget is built for s peed, s o
it's tags only.)

Flidget

I f you're running M ac O S X T iger (Vers ion 1 0 .4 ) with D as hboard,


you c an us e Flidget
(http://www.apple.c om/downloads /das hboard/blogs _forums /flidget.
D ownload the widget and double- c lic k it to add it to your
das hboard. C lic k the "i" ic on in the lower- right c orner to s et your
Flic kr login and pas s word.

You'll need to be s ure you have an A c tive Sc reen C orner s et for


D as hboard s o that you c an drag a file to the widget. To s et an
ac tive c orner, c lic k and hold D as hboard in your M ac D oc k and
c hoos e D as hboard P referenc es ... from the menu. C hoos e
D as hboard from one of the A c tive C orners .

O nc e you're s et to go, grab a photo you'd like to s end to Flic kr


and drag it to the ac tive c orner you s et up. You s hould s ee
Flidget appear on the s c reen. D rop the file onto Flidget. You'll
s ee a thumbnail of the image, and you c an add tags to the photo,
as s hown in Figure 1 - 3 2 .

Figure 1-32. Flidget Dashboard Widget for Mac


OS X
C lic k U pload, and Flidget will s end your photo to Flic kr.

Konfabulator

I f you don't have the lates t vers ion of M ac O S X, or if you're on a


Windows mac hine, you c an s till play along by us ing widget
engine Konfabulator (http://www.konfabulator.c om). O nc e you
have Konfabulator ins talled, you c an grab the Flic kr U pload
Widget from http://flagrantdis regard.c om/flic kr/uploader.php.

A s with Flidget, you c an s imply drag and drop an image file onto
the Flic kr U pload Widget. I n addition to tags , you c an add a title
and a des c ription and s et your privac y preferenc es before
c lic king U pload to trans fer the file, as s hown in Figure 1 - 3 3 .

Figure 1-33. Flickr Upload Widget for


Konfabulator
I f you find yours elf pos ting one or two photos at a time rather
than large s ets , thes e des ktop widgets might s peed up your
routine.

Beyond the Tools

I f the tools mentioned here aren't quite right for your Flic kr- flow,
you might want to inves tigate rolling your own [Hack #42] . T he
Flic kr A P I gives you programmatic ac c es s to all of Flic kr's
features , inc luding uploading photos , s o with a bit of
development you might be able to build your perfec t uploading
tool. A ls o, be s ure to look at the offic ial Tools page
(http://www.flic kr.c om/tools /) at Flic kr to find the lates t available
tools .
Hack 6. Post Pictures from Your Cell
Phone

Using Flickr's post via email f eature, you can send photos
directly f rom your cell phone while you're out and about.

I magine you're out walking around your c ity, and you notic e that
the annual fair is s etting up for its week- long extravaganza.
You'd like to s hare the news with your friends and family. You
c ould take a pic ture of the newly unloaded c arous el with your
digital c amera, walk home, trans fer the photo to your c omputer,
and then upload it to Flic kr. I f you have a c ell phone with a built-
in c amera, however, you c an take the pic ture and pos t it to Flic kr
on the s pot. H ooray for c onvergenc e!

To pos t from your c ell phone, you'll need a c ellular plan that lets
you s end photos via email. T he data- trans fer plans are us ually
$ 5 to $ 1 0 more per month than s tandard plans , or you might
have a pay- per- us e option that lets you pay for the number of
mes s ages you s end. C hec k with your c ellular s ervic e provider to
get details about s ending email from your phone. O nc e your plan
is in plac e, pos ting from your c ell phone relies on Flic kr's
"U pload- by- email" feature. M os t c amera phones c an s end any of
their photos via email. With the proper phone and plan, you
s imply need a Flic kr email addres s .

Uploading by Email
E very us er at Flic kr has a unique email addres s for uploading
pic tures . You c an find out yours by looking under Your A c c ount
at the bottom of any Flic kr page and c lic king the appropriately
titled "U pload- by- email" link. You'll s ee a page like the one in
Figure 1 - 3 4 , whic h lets you in on your s ec ret addres s .

Figure 1-34. A Flickr email address


N otic e that the email addres s is made up of random words and
numbers before the @ s ymbol, followed by photos .flickr.com. Keep
in mind that the domain is not s imply flickr.com, bec aus e without
the photos . prefix, your photos will be s ent into the void.

T he "U ploading by email" page als o lets you s pec ify any tags to
automatic ally add to a photo when it's uploaded via email.
P opular tags for c ell phone us ers inc lude cameraphone, mobile,
and moblog (s hort for mobile blog). I f you're going to be taking
photos from a s pec ific loc ation with your mobile phone, you
c ould inc lude the loc ation name as an auto- tag as well.

E very c ell phone has a different way of


taking pic tures and entering c ontac ts , s o
you might have to c ons ult your c ell phone
manual for s ome of thes e proc edures . T he
s c reens hots in this hac k s how a Sony
E ric s s on S7 1 0 aan exc ellent phone for
mobile photos .

While the page is s till up on your c omputer, grab your c ell phone
and s tart a new entry in your phone's c ontac ts lis t. I f you enter
your private Flic kr addres s now, you won't have to remember it
while you're out and about. Figure 1 - 3 5 s hows how entering the
addres s looks on a c ell phone; be s ure to add it to the email field
of a c ontac t.

Figure 1-35. Entering the Flickr address into a


phone
G ive the c ontac t a name you'll rec ognize, like Flickr, and you'll
be all s et for eas y uploading from the field. Be s ure to c lic k Save
on the "U ploading by email" page at Flic kr to as s oc iate your
Flic kr email addres s with your ac c ount.

Sending a Photo

So, you're out about town, armed with a c amera phone and a
Flic kr addres s s tored as a c ontac t. When you c apture the perfec t
image, you'll be s et for s haring it with the world.

E very c ell phone has a different method of s ending a photo, but


generally, the rule is to pus h buttons until you s ee an option
c alled Send (s ee Figure 1 - 3 6 ).

Figure 1-36. Choosing Send from picture options


O nc e you s elec t Send, you'll us ually have the option to review
the email before you s end it. I f you have great c ell- phone-
keypad dexterity, you c an s et a Subjec t line for your email like
the one s hown in Figure 1 - 3 7 , and Flic kr will us e the s ubjec t as
the title of the photo.

Figure 1-37. Editing a message subject


I f you don't s et a s ubjec t, mos t c ell phones us e the internal
filename of the photo as the s ubjec t of the mes s ages omething
along the lines of DSC00025. O f c ours e, you c an always c hange
the title of a Flic kr image onc e you're bac k at your home
c omputer.

When the mes s age is ready to go, c lic k Send, and your phone
will s end the mes s age through powerful c ell networks direc tly to
Flic kr. Your phone might even provide a Sending M es s age
graphic like the one s hown in Figure 1 - 3 8 to let you know the
mes s age is on its way.

Figure 1-38. Sending email via a cell phone


A minute or two later, your photo will appear on Flic kr with your
s ubjec t and pres elec ted tags , as s hown in Figure 1 - 3 9 .

Figure 1-39. A cell phone picture posted via


email on Flickr
T he entire proc es s of s ending a photo takes about a minute, and
then you c an s lip the phone bac k into your poc ket. O nc e you're
bac k at your c omputer, you c an log into Flic kr and add any
additional information, s uc h as a des c ription or more detailed
tags the hurdle of trans ferring the photo will be a dis tant memory.
Hack 7. Feed Your Latest Photos to Your
Web Site

Flickr provides a number of ways to syndicate your photos to


another web site.

A dding photos to an exis ting web s ite c an be a c omplex c hore.


You have to upload eac h photo to your s ite, write s ome H T M L to
dis play eac h photo on a page, and c reate duplic ate, res ized
images if you want to s how thumbnails of the photos .
Fortunately, there are s everal tools at your dis pos al that s implify
the proc es s of s haring your photos on a remote web s ite.

E ven though you upload your photographs to Flic krand they're


s tored on Flic kr's s ervers your photos aren't loc ked in at the
s ite. Flic kr is an open s ys tem that allows you to ac c es s your
photos in a number of ways and dis play them anywhere you'd
like. O ne of the eas ies t ways to s how your photos on another
s ite is with a Flic kr badge.

Flickr Badges

T hough it s ounds like s omething you might wear on your uniform,


a Flic kr badge is s imply a bit of c ode that dis plays photos on a
remote web s ite. Figure 1 - 4 0 s hows a s imple Flic kr badge with
three photos on a remote web s ite.
Figure 1-40. A Flickr badge on a remote site
You c an c reate your own Flic kr badge in a s imple five- s tep
proc es s . Brows e to the "C reate your own Flic kr badge" page
(http://www.flic kr.c om/badge_new.gne), and log in if you haven't
already. C reating a Flic kr badge is the proc es s of making a
number of dec is ions about the badge. H ere are the s teps :

Choos e the type

You c an dec ide between bas ic s tatic H T M L , or an


animated Flas h- bas ed badge. T he animated badge
s hows a bit of movement and fades thumbnails in and
out. C hoos ing Flas h will mean your vis itors will need the
M ac romedia Flas h plug- in ins talled for their brows ers in
order to s ee your photos .

Choos e the photos

You c an c hoos e to dis play your lates t photos , or any of


your photos that are tagged with a s pec ific term. I n
addition, you c an dis play photos from a group you're a
member of, all P ublic photos with a c ertain tag, or, if
you're feeling generous , all P ublic photos .

Set the layout (HTML only)

When you're building an H T M L badge, you have a


number of options for the layout. You c an c hoos e to s how
your pers onal buddy ic on, whic h links to your Flic kr
profile page. You c an c hoos e the number of photos you'd
like to s how, the s ize of the thumbnails , and the
orientation of the badge (horizontal or vertic al). Finally,
you c an c hoos e to s how the lates t photos or a random
s ampling.

Choos e colors

I f you want the badge to fit in s eamles s ly with your


remote s ite's des ign, you c an adjus t the bac kground,
border, and link c olors . T he preview at the bottom of the
page will s how your c hanges in progres s .

Copy and pas te code

O n the las t page, you c an preview your badge, and c opy


the c ode for your unique badge by highlighting it and
c lic king C trl- C .

T he c ode for a s tatic H T M L badge is a c ombination of C SS,


H T M L , and J avaSc ript. I t s hould look s omething like this :

<!-- Start of Flickr Badge -->


<style type="text/css">
#flickr_badge_source_txt {padding:0; font: 11px Arial, Helvetica,
color:#666666;}
#flickr_badge_icon {display:block !important; margin:0 !important;
border: 1px solid rgb(0, 0, 0) !important;}
#flickr_icon_td {padding:0 5px 0 0 !important;}
.flickr_badge_image {text-align:center !important;}
.flickr_badge_image img {border: 1px solid black !important;}
#flickr_www {display:block; padding:0 10px 0 10px !important;
font: 11px Arial, Helvetica, Sans serif !important; color:#399
#flickr_badge_uber_wrapper a:hover,
#flickr_badge_uber_wrapper a:link,
#flickr_badge_uber_wrapper a:active,
#flickr_badge_uber_wrapper a:visited {text-decoration:none !import
background:inherit !important;color:#3993ff;}
#flickr_badge_wrapper {background-color:#ffffff;border: solid 1px
#flickr_badge_source {padding:0 !important;
font: 11px Arial, Helvetica, Sans serif !important; color:#666
</style>
<table id="flickr_badge_uber_wrapper" cellpadding="0" cellspacing=
<tr>
<td>
<a href="http://www.flickr.com" id="flickr_www">
www.<strong style="color:#3993ff">flick
<span style="color:#ff1c92">r</span></strong>
.com</a>
<table cellpadding="0" cellspacing="10" border="0" id="flickr
<script type="text/javascript"
src="http://www.flickr.com/badge_code_v2.gne?count=3&display=lates
</script>
</table>
</td>
</tr>
</table>
<!-- End of Flickr Badge -->

T he C as c ading Style Sheet (C SS) s tyle definitions at the top of


the c ode format how the badge looks . You c an modify this C SS at
any point to c hange how the badge looks on your s ite.
I mmediately after the <style> tags , the s tandard H T M L <table>
holds the photos .

T he <script> tag does the work of dis playing the photos . A s you
c an s ee in the src attribute, the J avaSc ript file res ides at
http://www.flic kr.c om and dis plays photos bas ed on the
parameters pas s ed in the U RL . M any of the dec is ions you made
while running through the badge- c reation proc es s are
enc aps ulated in this U RL . For example, the count variable will be
s et to the number of photos you told the badge to dis play, and
the layout variable will be s et to v or h, depending on your c hoic e
of vertic al or horizontal layout.

I f you need to c hange your badge, try s tudying the fairly s elf-
explanatory variables in the U RL and c hanging their values . T hat
way, you c an make c hanges quic kly without running through the
whole badge- c reation proc es s again.

Flickr Feeds

A nother way that Flic kr makes photos available for us e on other


s ites is through s tandard XM L s yndic ation formats [Hack #17] .
You'll find news feeds at the bottom of many Flic kr pages that
relate to the c ontent you s ee on thos e pages .

E ac h Flic kr feed c ontains the 1 0 mos t rec ently added photos for
a partic ular us er, group, or tag. T he item nodes in the feed
c ontain all of the details you need to dis play the photo on a
remote s ite: the title, a link to the photo on Flic kr, and a bit of
H T M L for dis playing a thumbnail and c aption. H ere's a look at an
item in a Flic kr RSS feed (this example has been formatted for
readability; the ac tual feed inc ludes es c aped H T M L , with tags
s uc h as <p> rendered as the es c aped &lt;p&gt;):

<item>
<title>Ultimate Championships</title>
<link>http://www.flickr.com/photos/pb/16469233/</link>
<description>
<p><a href="http://www.flickr.com/people/pb/">pb</a> poste
<p><a href="http://www.flickr.com/photos/pb/16469233/"
title="Ultimate Championships">
<img src="http://photos10.flickr.com/16447365_40ac8021
width="240" height="161" alt="Ultimate Championships"
style="border: 1px solid #000000;" /></a></p>
<p>the women's championship game was washington vs. stanfo
</description>
<pubDate>Mon, 30 May 2005 11:01:15 -0700</pubDate>
<author>nobody@flickr.com (pb)</author>
<guid isPermaLink="false">tag:flickr.com,2004:/photo/16469233<
</item>

T he <title> and <link> elements hold the title of the photo and a
link to the photo, as you'd expec t. T he <description> element
holds the bloc k of H T M L that you c an us e on a remote s ite.

T he mos t c ommon us e of RSS is viewing new items in a


news reader, but there's no reas on you c an't us e this s ame feed
to c reate a c us tom Flic kr badge. P ars ing XM L is the perfec t job
for P erl, and with a few lines of c ode, you c an build your own
badge.

The code

T his P erl s c ript us es the LWP::Simple module to fetc h a Flic kr


feed and the XML::RSS module to pars e the feed and dis play its
c ontents . M ake s ure you have thes e modules on your s erver, and
then add this c ode to a file c alled flickr_feed.pl. Be s ure to
inc lude a valid Flic kr feed U RL that c ontains the photos you want
to s yndic ate.

#!/usr/bin/perl
# flickr_feed.pl
# Transforms a Flickr Feed into HTML
# Usage: flickr_feed.pl

use strict;
use XML::RSS;
use LWP::Simple;

# Grab the feed.


my $flickr_feed = 'insert Flickr feed URL';
my $feed = get($flickr_feed);

# Start RSS Parser


my $rss = new XML::RSS;

# parse the feed


$rss->parse($feed);

# initialize item counter


my $i;

# print the title, link, and description of each RSS item


foreach my $item (@{$rss->{'items'}}) {
$i++;
my $desc = "$item->{'description'}\n";

# remove the "posted by" text


$desc =~ s!<p>.*?posted a photo:</p>!!;

# use thumbnails instead of medium images


$desc =~ s!_m!_t!;

# remove the width and height attributes from image tags


$desc =~ s!width=".*?" height=".*?"!!;
# remove the paragraph tags
$desc =~ s!</?p>!!g;

# print the item


print "$desc<br />";
print "<a href=\"$item->{'link'}\">";
print "$item->{'title'}</a><br /><br />";

# set the number of photos


last if ($i == 3);
}

T his c ode downloads the Flic kr feed and mas s ages the H T M L in
the <description> tag, removing s ome text. I t then prints eac h
item in the feed, until it hits the number s pec ified in the las t line
of the s c ript.

Running the hack

You c an run this c ode from the c ommand line by c alling the
s c ript like this :

perl flickr_feed.pl

You'll probably want to s et the s c ript to run on a regular


s c hedule with the Windows Tas k Sc heduler, or cron on U nix-
bas ed s ys tems .
U s ing an XM L feed ins tead of a preprogrammed Flic kr badge
requires a bit more work, but it gives you more c ontrol over the
pres entation. You c an c reate your own C SS s tyles and c las s es
to make the photos appear exac tly as you want them to. Figure
1 - 4 1 s hows a c us tom Flic kr badge c reated with the s c ript
provided in this hac k, viewed on a remote s ite.

Figure 1-41. A custom Flickr badge


Hacking the Hack

E ven though the Flic kr feeds c ontain mos t of the information


as s oc iated with eac h photo, you c an s till do more with the Flic kr
A P I . T he A P I provides programmatic ac c es s to anything at
Flic kr, not jus t photos . (You c an read the full doc umentation at
http://www.flic kr.c om/s ervic es /api/.)

I n addition to titles and c aptions , you c an get ac c es s to


everything from the number of c omments people have left about
a photo to notes left by others to tec hnic al data (E XI F tags ) from
the c amera that took the photo. Building a c us tom badge with
the A P I will be more tec hnic ally c omplex than pars ing an RSS
feed, but if you really want ac c es s to all of the data you have
s tored at Flic kr, it's available!
Hack 8. Make a Photo Gallery in 30
Seconds or Less

This online f orm will create ready-to-paste HTML code f or your


next photo gallery.

T here are a number of tools available for building galleries or


albums from your Flic kr photos . O ne of my favorite free tools is
C K's Flic kr A lbum M aker, whic h c an be found at
http://webdev.yuan.c c .

C K is a Taiwanes e Flic kr H ac kr who has


made an exc ellent c ollec tion of c ode
generators , mos t of them driven by forms .

C K's Flic kr A lbum M aker pres ents an online form in whic h you're
reques ted to fill out a few fields . I t then produc es either a s tatic
gallery of your photos , or a s lides how. I n both c as es C K
provides you with the H T M L c ode, s o you c an c opy it and pas te
it into your own web s ite.

Sinc e C K's c ode talks to the Flic kr A P I to get information about


your photos , you don't need to ac tually know anything about the
A P I yours elf. A ll of that s tuff happens under the hood.

Making an Album

To begin making an album, go to C K's s ite at


http://webdev.yuan.c c and c lic k on the Flic kr A lbum M aker
navigation link. You'll be pres ented with the form s hown in Figure
1 -4 2 .

Figure 1-42. CK's Flickr Album Maker


A fter filling out the form with the pers onal information needed to
ac c es s your Flic kr photos , pres s the s ubmit button. C K's A lbum
M aker will then produc e a s ample album and provide you with the
H T M L s ourc e c ode for c opying, as s hown in Figure 1 - 4 3 .

Figure 1-43. CK's Album Maker-the result


I f you want to tweak the res ult, you c an modify the embedded
s tyles heet.
Making a Slideshow

I f you s elec t the Slides how option at the top of C K's form, it will
produc e s ourc e c ode for a very s piffy interac tive s lides how,
ins tead of a s tatic gallery. T he s lides how will look s omething like
Figure 1 - 4 4 .

Figure 1-44. Flickr Slideshow


I f the s lides how interfac e looks familiar, it's bec aus e you've
probably s een it before. T his is the s ame Flas h- bas ed s lides how
us ed on the Flic kr web s ite. I f you look at the s ourc e c ode that
C K produc es , you'll notic e that it is merely s ummoning Flic kr's
s lides how and putting it into an iframe:

<iframe width="500" height="500" frameborder="0" scrolling="no" sr

A nother nic e tool for adding a Flas h


s lides how to your web s ite is the $ 2 0
Slides how P ro, whic h c an be found at
http://www.s lides howpro.net.

Rolling Your Own

T here are a few other web s ites that work in a s imilar way. A lot
of C K's s tuff either us es or is ins pired by O berkampf, a P H P
library of us eful routines for building s lides hows and galleries .
T he O berkampf web s ite
(http://www.entrauge.c om/tools /oberkampf/index.php) als o
employs an online form to c ollec t your pers onal information,
whic h it then embeds direc tly into a pers onalized c opy of the
O berkampf s ourc e c ode.

A rmed with O berkampf, you c an reduc e the tas k of produc ing a


s trip of your thumbnail images to a s ingle line of P H P c ode.

See Also

C K provides exc ellent s upport for the A lbum M aker and


other tools he makes . H e has c reated a Flic kr group for
this purpos e at
http://www.flic kr.c om/groups /flic kr_tools /.
Hack 9. Post Photos to Your Blog

If you take a f ew minutes to enter some inf ormation about


your weblog at Flickr, you can post photos directly to it with a
single click.

M any weblog s ys tems offer tools to help you upload and inc lude
images with your pos ts , bit you might find that Flic kr is a nic e
alternative to the s tandard photo tools . O nc e you upload a photo
to Flic kr [Hack #1], you have s everal options for inc luding that
photo in your weblog pos ts .

Blog This

T he mos t direc t way to s end a photo from Flic kr to your weblog


is through the Blog T his button that you'll s ee above eac h of
your photos , as s hown in Figure 1 - 4 5 .

Figure 1-45. The Blog This button above a photo


at Flickr
To enable the Blog T his button, you need to give Flic kr s ome
information about your weblog.

Configuring a weblog

Setting up Flic kr to pos t to a weblog is a s imple three- s tep


proc es s . C lic k Your A c c ount at the top of any page at Flic kr, and
c lic k Your Blogs under the s ec tion labeled Blogging. You'll find a
lis t of any weblogs you've s et up; to add a weblog to your
ac c ount, c lic k "Set up a new blog."

T he firs t s tep to s etting up a new weblog is telling Flic kr whic h


weblog tool you us e. Flic kr s upports the following weblog
s ys tems :

Blogger

http://www.blogger.c om

TypePad

http://www.s ixapart.c om/typepad/

Movable Type

http://www.s ixapart.c om/movabletype/


LiveJournal

http://www.s ixapart.c om/livejournal/

WordPres s

http://www.wordpres s .org

Manila

http://www.manilas ites .c om

I f you us e a weblog tool that's not lis ted, c hec k your tool's
doc umentation to s ee if it us es one of the s upported weblog
applic ation programming interfac es (A P I s ). A n A P I allows a
third- party tool s uc h as Flic kr to add pos ts to your weblog. Flic kr
s upports the following A P I s :

Atom

T his A P I is an emerging independent s tandard for


programmatic weblog ac c es s and is s upported by many
tools , inc luding Blogger and the lates t vers ions of
M ovable Type. You c an s ee the details of the A P I at
http://www.atomenabled.org.

BloggerAPI

T his was the firs t weblog A P I implemented by Blogger.


I t's no longer ac tively developed, but s ome tools s till
s upport it.

MetaWeblogAPI

T his is another older A P I that s ome tools , inc luding


WordP res s , s upport. You c an read more about the A P I at
http://www.xmlrpc .c om/metaWeblogA pi.

I f your weblog tool s upports one of thes e A P I s , you jus t need to


know the API Endpoint: a U RL to whic h Flic kr s hould s end A P I
reques ts . T he doc umentation s hould give you the A P I E ndpoint
U RL , and with that in hand, you c an move on to the s ec ond s tep.

O nc e you've c hos en your tool or s upported A P I , you'll need to


enter the us ername and pas s word you us e for your weblog. Flic kr
will us e this information to c ontac t the weblog tool and fetc h
information about your weblog (or the multiple weblogs you
maintain there).

C hoos e your weblog from the lis t, c lic k N ext, and verify the
information on the following page. I f you don't feel c omfortable
s toring your weblog tool's pas s word with Flic kr, you c an unc hec k
the box labeled "Store your pas s word? " C lic k A ll D one, and
you'll be ready to s tart pos ting pic tures !

Posting to your weblog

With your weblogs s et to go at Flic kr, brows e to one of your


photos that you'd like to pos t to a weblog. C lic k the Blog T his
button above the photo and c hoos e one of your weblogs from the
lis t, as s hown in Figure 1 - 4 6 .
Figure 1-46. Choosing a blog with the Blog This
button

O nc e you c hoos e your weblog, you'll have the option to c ompos e


your pos t at Flic kr (Figure 1 - 4 7 ).

Figure 1-47. Composing a weblog post at Flickr


C lic k P os t E ntry, and Flic kr will automatic ally s end the text and
photo to your weblog. Figure 1 - 4 8 s hows the example pos t at a
Blogger- powered weblog.

Figure 1-48. A weblog post via Flickr


T he nic e thing about us ing Flic kr's Blog T his feature is that you
don't have to write the H T M L nec es s ary to link to a photoyou
c an s imply point and c lic k to add a pos t with a photo to your
weblog, and Flic kr as s embles the nec es s ary H T M L behind the
s c enes .

I f you want to c hange the H T M L that Flic kr us es , you c an alter


the way Flic kr lays out the photo and text for your weblog pos ts .
To c us tomize a pos t layout for one of your weblogs , brows e to
the Your Blogs page at Flic kr and c lic k L ayout. You'll s ee s everal
options , as s hown in Figure 1 - 4 9 .

Figure 1-49. The weblog post layout options at


Flickr
You c an even c reate a c us tom pos t layout template, if you want
to go beyond the exis ting options .

Roll Your Own Post

While the Blog T his feature at Flic kr works well for pos ting a
s ingle photo along with s ome text, it does n't work as well for
pos ting multiple photos within a s ingle pos t. A nd you might find
that your pos t layouts are s o unique that a s ingle template won't
work. I n either of thes e c as es , you'll need to write your own
H T M L to dis play images in your weblog pos ts . E ven though
you'll be doing s ome of the work on your own, Flic kr c an s till
make your life eas ier by hos ting and proc es s ing your images .

T he key to writing your own H T M L to dis play images is finding


direc t U RL s for the images you upload. But eac h image has more
than jus t one U RL for every image you upload to Flic kr, there are
five image s izes available, eac h with its own U RL . T his lets you
c hoos e the appropriate image s ize for the pos t, or us e a
thumbnail ins tead of a full image.

Keep in mind that the larger your photo is ,


the longer it will take your readers to
download it. A nd large photos won't always
fit within the des ign c ons traints of a
s tandard weblog. I f your weblog text fits
within a 4 0 0 - pixel- wide c olumn, pos ting
an 8 0 0 - pixel- wide photo will break the
des ign.
To find U RL s for eac h of the image s izes available, c lic k the
appropriately titled A ll Sizes button above any photo you've
uploaded to Flic kr. T his will take you to the A ll Sizes page
(Figure 1 - 5 0 ), whic h inc ludes the s ize options lis ted ac ros s the
top of the page, along with the dimens ions of the photo in eac h
s ize.

Figure 1-50. The All Sizes page for an image at


Flickr
A s you c lic k eac h image s ize in the menu, you'll find a unique
U RL lis ted underneath the photo. E ac h U RL has a s imilar format
that looks s omething like this :

http://photos11.flickr.com/17447365_fff01711bb_o.jpg

N otic e that the U RL s tarts with a Flic kr domain and that the
filename inc ludes two alphanumeric I D s s eparated by an
unders c ore, followed by a final letter (again s eparated by an
unders c ore) before the .jpg extens ion. T hat final letter is a URL
code, whic h repres ents the s ize of a Flic kr photo; unders tanding
the c odes c an help you c reate or c hange links to different photo
s izes on the fly. H ere's a quic k look at the different photo s izes
available at Flic kr:

Large

T his s ize is the original s ize of the photo before it was


uploaded to Flic kr. I f you uploaded a photo that was 8 0 0
pixels wide by 6 0 0 pixels high, you c an ac c es s the
original by c lic king the L arge s ize. T he U RL c ode for this
s ize is o, whic h probably s tands for original. I f the
original image you uploaded was extremely large (more
than 1 0 2 4 pixels at its longes t dimens ion), an O riginal
photo s ize will als o be available at Flic kr. I n this c as e,
the L arge s ize will have the U RL c ode b, and the O riginal
s ize will have the c ode o.

Medium
T he M edium s ize is what you s ee on a Flic kr photo detail
page. T his s ize will be 5 0 0 pixels at its longes t
dimens ion, depending on the orientation of the photo.
T here is no U RL c ode for M edium photos , bec aus e this
is the default s ize.

Small

Small photos are 2 4 0 pixels at the longes t dimens ion


and are us ed on photos tream pages as thumbnails . T he
U RL c ode for Small photos is m.

Thumbnail

T his s ize is 1 0 0 pixels at its longes t dimens ion and c an


be us ed to link to a larger vers ion of the photo. T he U RL
c ode for T humbnail- s ized photos is t.

Square

A Square photo is a vers ion of the original c ropped to a


7 5 x7 5 - pixel s quare. You'll find this s ize photo in us e on
your Flic kr homepage when you're logged in. I t's a handy
s ize to us e if you need to know the exac t width and
height of a photo. T he U RL c ode for s quare photos is s.

O nc e you've determined the s ize of the photo you'd like to


dis play in your pos t, c opy its U RL . T hen, you c an us e the U RL in
an H T M L image tag to dis play the photo, like this :

<img src="http://photos11.flickr.com/17447365_fff01711bb_m.jpg" wi
When you're writing your own H T M L , you c an c ombine multiple
images , link images to unique web pages , or c reate more
c omplex layouts than are pos s ible with Flic kr's Blog T his
feature. Figure 1 - 5 1 s hows a s ingle pos t at L iveJ ournal with
s everal photos hos ted at Flic kr.

Figure 1-51. A post at LiveJournal with images


hosted at Flickr
While you might not need this level of c ontrol for every pos t you
make, knowing what's available to you c an give you the freedom
to get c reative with your weblog pos ts .
Chapter 2. Tagging Photos

H ac ks 1 0 - 1 4

H ac k 1 0 . D es c ribe Your P hotos

H ac k 1 1 . P lay with Tags

H ac k 1 2 . G eotag Your P hotos

H ac k 1 3 . E xploit C ompound Tags

H ac k 1 4 . M ake a Flic kr- Style Tag C loud


Hacks 10-14
Before web applic ations borrowed the term tags to mean
keywords about piec es of digital information, we thought of tags
as s omething you added to a produc t to give a bit more
information. For example, you might add a s ale tag to a s hirt to
let everyone know its new pric e.

P hoto tagging is n't muc h different, in the s ens e that you're


adding keywords to a photo to let everyone know a little more
about that photo (and to provide terms that people c an s earc h
for to find photos of s pec ific s ubjec ts ). You c an think of tagging
as a way of des c ribing your photos [Hack #10] for a larger
audienc e, while organizing them for your own us e.

I magine you have a pic ture of a s hirt, and you'd like to be able to
find that pic ture in the future. I f you add a few tags to the photo,
s uc h as s hirt, clothes , or fas hion, when you want to s ee that
pic ture in the future you c an s imply brows e your tags and view
all of your photos tagged with s hirt as a s eparate c ollec tion of
photos . A ls o, anyone els e interes ted in pic tures of s hirts will be
able to s ee your photo as part of the larger, global c ollec tion of
photos tagged with s hirt.

Flic kr was one of the firs t applic ations on the Web to allow
tagging of c ontent, and Flic kr members have c ome up with many
ways to us e tagging to their advantage. Some have c reated
alternate interfac es and games [Hack #11] for brows ing global
tag c ollec tions . O thers have found a way to us e tags to indic ate
the loc ation a photo was taken [Hack #12] . You c an als o us e
Flic kr's tags to c reate your own vis ualizations of how people are
us ing tags [Hack #14] .

Whether you're tagging photos for pers onal organization or to


take part in the larger Flic krvers e, you'll find you c an improve
the way you tag by s eeing how others are us ing tags to c reate
new s pac es for s haring photos .
Hack 10. Describe Your Photos

Taking some time to think about how you describe your photos
on Flickr might help you f ind a wider audience f or your pictures.

A photo might be worth a 1 ,0 0 0 words , but you c an't extrac t


thos e words from a photo automatic ally. To pool like photos
together, Flic kr needs your words , and there are s everal ways to
des c ribe your photos s o that you c an organize them and plac e
them within their proper s pac es in the larger Flic kr ec os ys tem.

Titles and Descriptions

T he mos t obvious photo des c riptors you c an us e in Flic kr are


photo titles and des criptions . T itles are lis ted above photos and
are us ually jus t a few words long. D es c riptions appear under
photos and c an be anything that won't fit into a s hort title. You
c an des c ribe the photo in a few s entenc es , or tell an entire s tory
about the photo in a few paragraphs .

You c an add titles and des c riptions when you upload a photo, or
later (s imply c lic k the "E dit title, des c ription, and tags " link to
the right of the photo on the detail page). You c an als o edit them
at any point by s imply c lic king the title or des c ription. Figure 2 -
1 s hows what editing a title looks like.
Figure 2-1. Editing a photo title
C lic k Save onc e you've made your c hanges , and your new title
or des c ription will be s et.

I n addition to appearing with the photo in your Flic kr


photos tream, keep in mind that the photo title will be available in
group photo pools , on your c ontac ts ' photo pages as they hover
over a thumbnail of the photo, and anyplac e on Flic kr where your
photo is s hown. I n other words , the title will be as s oc iated with
your photo in many ways . Your des c riptions will als o appear in
Flic kr news feeds [Hack #17] .

Tags

Tags are keywords you c an add to your photos . T here are two
main reas ons to add tags to your photos . T he firs t is for your
own c ategorization. I f you tag every photo of your c at that you
pos t to Flic kr with the word cat, you c an ins tantly view all of
thos e photos in a group by c lic king on your cat tag. T he other
reas on to tag photos is to take part in the larger c ommunity of
Flic kr us ers . By c lic king the global cat tag, you c an s ee other
photos that people have tagged with that keyword.

Tags appear to the right of a photograph, and you c an add them


to your own photos at any time by c lic king the "A dd a tag" link.
Figure 2 - 2 s hows a photo tagged with the words cameraphone and
watermelon.

Figure 2-2. Tags on a photo at Flickr


A s des c ribed above, tags are als o links . C lic k one to s ee all of
your photos that you've tagged with that word or phras e, and
c lic k the globe ic on to s ee all the Flic kr us ers ' photos that s hare
that tag. O n the global tag page, you'll s ee the lates t photos
tagged with that partic ular word or phras e, and clus ters , or
groups of related tags . Figure 2 - 3 s hows the c lus ters page for
the watermelon tag.

Figure 2-3. A tag clusters page at Flickr


O nc e you get into the habit of tagging your photos , you'll find
that tags c an help you navigate your own c ollec tion of photos .
But the art of tagging c an be awkward at firs t, s o here are s ome
rules to keep in mind.

Tag selfishly, think globally

T hough you c an tag for the c ompletely s elfis h reas on of


organizing your own c ollec tion of photos , keep in mind that
others might be interes ted in your photos . I f your tags are
c ompletely unique or made- up words , it might be hard for others
to find your photos . I f you us e fairly generic words , you c an be
s ure they'll be inc luded on related global tag pages .

I f you don't want your photos to be found, you s hould tag


c arefully or s kip the tagging altogether. Tagging is a way of
drawing attention to your photos , and if you want to s hare your
photos with the world but don't want them to s how up on global
tagging pages , you s hould leave off the tags . (O f c ours e, you c an
always mark your photos P rivate [Hack #2], and tag for yours elf
without attrac ting any attention to your photos .)

Describe what you see in the photo


(mostly)

Tags are mos t often us ed to des c ribe what appears in a


photograph, but not nec es s arily everything that appears . For
example, Figure 2 - 2 s hows s omeone s lic ing a watermelon. I n
addition to the watermelon, the photo inc ludes hands , a large
knife, a c utting board, and a kitc hen c ounter, but the only tag
that's needed to c apture the es s enc e of the photo is watermelon.
T he photo might dis appoint s omeone looking for pic tures of
kitc hen c ounters , but not s omeone looking for pic tures of
watermelon.

Describe how you took the photo

I n addition to the main s ubjec t of a photo, many people inc lude


details about the photo that aren't immediately apparent. T he
photo in Figure 2 - 2 als o inc ludes the tag cameraphone, whic h
indic ates s omething about the c amera us ed to take the photo. I f
s omeone were looking for pic tures of c ameraphones , this photo
wouldn't fit the bill, but there's no reas on you c an't tag your
photos with a keyword indic ating the type of c amera you us ed to
take the photo.

You'll als o find many photos tagged with the name of the loc ation
where the photo was taken; it might make s ens e to tag a photo
with a plac e name, es pec ially if the photo is a s hot of a s pec ific
area. (T he photo in Figure 2 - 2 was taken in O regon, but as the
photo is not s pec ific ally related to O regon in any way, an Oregon
tag was n't inc luded.)

Get suggestions

O ne way to improve your tagging s kills is to look at s ugges tions


for related tags . Flic kr does n't s ugges t related tags , but if you
us e the Firefox brows er, a G reas emonkey s c ript by A lan Taylor
(Flic kr member kokogiak) c an help you tag your photos .

M ake s ure you have the G reas emonkey plug- in


(http://greas emonkey.mozdev.org), and then ins tall the s c ript by
brows ing to
http://www.kokogiak.c om/webtools /greas emonkey/flic krelatedtags
and c hoos ing Tools I ns tall T his U s er Sc ript... from your
brows er's menu. With the s c ript ins talled, brows e to the photo
upload page at Flic kr, enter a tag, and c lic k the new See Related
Tags link pic tured in Figure 2 - 4 .

Figure 2-4. See Related Tags on the Flickr


upload page
Seeing related tags c an often s park ideas for tags you c an add
to your photos .

Browse tags regularly

O ne of the bes t ways to learn how to tag photos is to s ee how


others are us ing tags . C lic k the Tags link at the top of any Flic kr
page to s ee the mos t popular tags in us e ac ros s Flic kr. With a bit
of s c ripting, you c an als o s ee whic h tags are mos t popular
among your friends [Hack #26] .

O nc e you add a tag to one of your photos , c lic k the globe ic on


for that tag and s ee if your photo makes s ens e within the larger
s et. Watc hing the global pages for the tags you us e is another
great way to get a s ens e for what to tag and what not to tag.

Don't spam

A c ompletely open tagging s ys tem s uc h as Flic kr's is extremely


flexible, but it c an als o be abus ed. I f you want to be a good Flic kr
c itizen, you s hould keep your tags related to your photos . I f your
photo is n't remotely related to a s uns et, why tag your photo with
s uns et? I f you think in terms of what's us eful for your own
c ategorization, c hanc es are your tags will blend perfec tly with
the larger Flic kr c ommunity and you won't be tag- s pamming.

Notes
P ointing out a s pec ific part of a photograph is s omething we do
all the time when we're s haring print photos with people fac e to
fac e. We point out s pec ific people in a photo that s omeone els e
does n't know, or a c ritic al portion of the photo that s omeone
s hould s tudy more c los ely. But when we're s haring photos on the
Web, it's not as eas y to point out jus t a portion of a photo. T hat's
where Flic kr notes c ome in handy.

Notes are one of the mos t unique features of Flic krthey provide
the ability to annotate photos by highlighting a portion of the
photo and inc luding brief text notes about that s ec tion. A s
vis itors hover their mous e pointers over a photograph, they c an
s ee the note for a partic ular region of the photo. I t might not be
immediately apparent why you'd need to annotate a s pec ific
s ec tion of a photo when you c an inc lude extended des c riptions
and tags with eac h photo, s o let's look at s ome of the reas ons
you might want to do s o.

Describe everyone in a photo

I f you have a group photo, you c an us e notes to highlight


everyone in the photo and inc lude their names . You c ould do the
s ame with a photo des c ription, but the notes provide a more
immediate way for viewers to s ee who's who, rather than going
bac k and forth between the photo and c aption and c ounting
people in a lis t of names .

Make personal maps


A nother interes ting us e of notes is for annotating maps with
pers onal s tories . I n A pril 2 0 0 5 , M att H aughey (Flic kr member
mathowie) pos ted a s atellite image of his c hildhood
neighborhood and us ed the notes feature to highlight areas and
tell s tories about them. Figure 2 - 5 s hows the original image.

Figure 2-5. Using notes on a map at Flickr


T he res ulting memory map was very popular, and numerous Flic kr
us ers have done the s ame s inc e. You c an find hundreds of
memory maps by looking at the global memorymap tag page
(http://www.flic kr.c om/photos /tags /memorymap/). I n addition to
c hildhood memories , you c ould us e Flic kr to annotate maps in
this way for planning or rec ounting the details of a trip, s haring
your favorite walk in your hometown, or dis c us s ing loc ations with
others .

Link photos together

Bec aus e you c an us e H T M L links within notes , it's pos s ible to


s tring a s eries of photos together us ing links in notes . For
example, you c ould take a wide- angle photo of a lands c ape in
one photo, and us e a note to highlight a s pec ific element of the
lands c ape. Within that note, you c ould link to a c los e- up photo of
that element, as a way of zooming in on the element you want to
highlight.

Flic kr member G us tavoG us ed linking notes to build a


"walkthrough" of a part of Seattle. You c an s ee the res ults at
http://www.flic kr.c om/photos /gus tavog/2 2 0 5 4 2 4 1 /.

Collaborate

N otes c an als o be a c ollaborative ac tivity, and you c an us e them


to s hare thoughts with others . You c an s pec ify whether or not
other Flic kr us ers c an add notes to your photos by c lic king the
P hoto P rivac y link under Your A c c ount at the bottom of any
Flic kr page. I f you allow others to pos t notes , you c ould end up
with s omething like the annotated vers ion of the M erode
A ltarpiec e that a group of A rt H is tory s tudents put together
(http://flic kr.c om/photos /ha1 1 2 /9 0 1 6 6 0 /in/s et- 1 2 9 0 0 6 /).

Summary

E ffec tively des c ribing your photos at Flic kr is a fairly eas y tas k,
but it's one that c an benefit from s ome forethought. T hinking
about how your photos fit with the larger c ommunity will help you
c onnec t with other Flic kr members and organize your photos
more effic iently.
Hack 11. Play with Tags

Photo tags let you explore photos around a specif ic theme at


Flickr, and thanks to the Flickr A PI, several applications let you
explore Flickr photos interactively.

T he Flic kr A P I gives developers ac c es s to the photos s tored


there, and many developers have imagined new ways to view
photos . P hoto tags have given developers a new way to arrange
photos in third- party applic ations .

H ere are a few interac tive examples that will give you a s ens e of
how others are reus ing Flic kr images . By playing s ome of thes e
games , you'll s ee how Flic kr images c an be us ed in new ways
(and probably have s ome fun in the proc es s ).

Memry

Remember thos e memory games you played as a kid, where you


had to turn over c ards of matc hing pic tures ? Spanis h developer
A nna Fus ter Fabre has rec reated the game with Flic kr images
and Flas h. To play, you'll need the Flas h P layer, whic h you c an
download from http://www.mac romedia.c om/flas hplayer/ if you
don't already have it. With Flas h in plac e, brows e to
http://www.pimpampum.net/memry/enter.php, enter any tag, and
c lic k "play! " to s tart your game.
You'll s ee a 4 x 4 bloc k of white tiles . C lic king a tile reveals an
image that has been gathered from the Flic kr A P I . Somewhere
under another tile is the s ame image, and it's your mis s ion to
find all of the matc hes in as few plays as pos s ible. T he blue
plays c ount lets you know how many times you've c lic ked on
tiles . Figure 2 - 6 s hows a game in progres s for the tag infrared.

Figure 2-6. Memry game using the tag "infrared"


I f you get frus trated and want to s ee what's under the tiles , c lic k
the "finis h" link on the right s ide of the page. For a more
c hallenging game, reload the page or c lic k the "s tart again" link,
and c hoos e the 6 x 6 option.

You c an us e any tag you like, but patterns make for partic ularly
diffic ult matc hing. I f you c an't think of any tags , try bricks , leaf,
fractal, or texture.

When you're finis hed with a game, you c an c lic k on any of the
photos to view the full photo on Flic kr. A nd if you want to s hare a
partic ular game, you c an add a tag to the U RL to bring up that
tag immediately, like this :

http://www.pimpampum.net/memry/enter.php?tag=infrared

Replac e infrared in this example with any tag of your c hoic e.


A fter a few games , you might even begin to remember where
you've left your keys .

flickrTagFight

G erman developer N ils K. Windis c h (Flic kr member netomer)


thought it would be fun to pit two tags agains t eac h other to s ee
whic h is us ed mos t often ac ros s Flic kr. When you brows e to
flic krTagFight (http://www.netomer.de/flic krtagfight/), you'll find
two blank fields . Fill them in with any two tags and c lic k "fight" to
s ee whic h tag is more popular. Figure 2 - 7 s hows kitten and puppy
going to head to head.
Figure 2-7. "Kitten" vs. "puppy" at
flickrTagFight
Bes ide eac h tag is the total number of times photos have been
tagged with that partic ular word. T he winner is s hown in pink, the
los er in blue. You'll als o s ee the las t 1 5 photos tagged with eac h
tag. C lic k a photo to s ee the larger vers ion at Flic kr.

I f you'd like to link to a partic ularly interes ting battle to s hare


with others , you c an us e the following format:

http://netomer.de/flickrtagfight/kitten.puppy.fight

Replac e the words kitten and puppy in this example with the two
tags you'd like to s ee ins tead.

Related Tag Browser

T he Flic kr Related Tag Brows er is an interac tive Flas h


applic ation by A irtight I nterac tive
(http://www.airtightinterac tive.c om). To us e it, make s ure the
Flas h P layer is ins talled for your brows er, and go to
http://www.airtightinterac tive.c om/projec ts /related_tag_brows er/a
You'll find a blank field; type any tag and c lic k G o.

When the Brows er s tarts , you'll s ee the tag you c hos e in the
c enter s urrounded by a c irc le of around 5 0 related tags . For
example, if you typed in the tag water, you'll find related tags
s uc h as waves , pool, waterfall, ocean, and river. C lic king a related
tag will put that tag in the c enter and s how further related tags in
the c irc le.
A ny tag in the c enter inc ludes a bloc k of 3 6 rec ently added
photos that have that tag. C lic king on a photo will bring up a
larger vers ion of the photo, as s hown in Figure 2 - 8 .

Figure 2-8. Browsing "grainy" with the Related


Tag Browser
I f you want to s ee a partic ular photo at Flic kr, bring up the larger
s ize and c lic k the V iew Flic kr P hoto P age link. You'll go to that
photo's detail page at Flic kr in a new brows er window. A s you
move the pointer around the applic ation, you'll s ee the tags or
photos zoom in or out following your foc us , giving the applic ation
a very interac tive feel.

U s ing the Related Tag Brows er is a radic ally different experienc e


from brows ing tags at Flic kr, and the Flic kr A P I has made
reinventing its interfac e pos s ible. T hes e games c ould never
replac e Flic kr for brows ing photos , but they s how what's pos s ible
with the c ombination of tagging and an open platform like Flic kr.
Hack 12. Geotag Your Photos

You can use Flickr tags to describe the exact location where you
took a photo, and then display your geographically precise
photos on a map.

A ny loc ation on E arth c an be addres s ed with a s et of two-


number c oordinates c alled latitude and longitude. While you
probably learned about c oordinates in s c hool, c hanc es are you
haven't had muc h need for reading them, unles s you make maps
or go hiking in the wildernes s . With the proliferation of handheld
G P S units and online maps , though, latitude and longitude have
wandered bac k into our everyday voc abularyand into the world of
Flic kr photos .

U s ing Flic kr's tagging features [Hack #10], s ome members


des c ribe the exac t latitude and longitude of their pos itions on
E arth when they took partic ular photos . T his prac tic e is c alled
geotagging, and it c an lead to fun ac tivities s uc h as viewing your
photos on a map and finding other photos that were taken in
s pec ific loc ations .

T he rec ipe for geotagging your photos is s imple. N ote the


loc ations where you take your photos , upload them to Flic kr, and
add three s pec ific tags to the photos with the following formats :

geo:lat=latitude
geo:lon=longitude
geotagged
T he geotagged tag lets others know that the photo has been
given a s pec ific loc ation, and the other two tags des c ribe that
loc ation. A s you know, latitude and longitude aren't exac tly
found on every s treet s ign, s o the work involved with geotagging
is finding out your c oordinates .

Without a GPS Unit

Your firs t thought might be to rus h out and buy a handheld G P S


unit or a c utting- edge c amera with G P S built in, and thos e are
indeed great ways to find out your latitude and longitude at any
given moment. H owever, there are als o s ome free mapping tools
on the Web, s uc h as G eoc oder.us , that you c an us e to find out
where you are or where you've been.

I f you're taking photos in a c ity, your tas k is fairly s imple: take a


notebook with you and write down c ros s s treets or addres s es as
you take photos . You c an eas ily find the c oordinates for jus t
about any addres s or inters ec tionto try it out, s imply brows e to
http://geoc oder.us and type in an addres s or inters ec tion, along
with the c ity and s tate.

For example, entering the phras e " 23rd and Lovejoy ST, Portland
OR" will give you a map of P ortland, and the latitude and longitude
for that loc ation: 4 5 .5 2 9 7 4 , - 1 2 2 .6 9 8 3 0 7 . O nc e you have the
c oordinates , you c an add your three tags to your photo taken in
that loc ation, as s hown in Figure 2 - 9 .

Figure 2-9. A geotagged photo at Flickr


I f you're taking photos in the O regon bac kc ountry, or at any
loc ation without a s treet addres s , you'll probably need to turn to
G P S if you want to inc lude prec is e c oordinates .

With a GPS Unit

T he only tric k to c oordinating a handheld G P S unit and a digital


c amera is s ync hronizing their c loc ks . By looking at E XI F data
[Hack #3] embedded in your photos and c oordinating it with your
G P S trac k logs , you'll be able to tell exac tly where you were
when you took any of your photos .

E ac h G P S unit will have its own method for looking at trac k logs
from an outing, s o you'll need to c ons ult your manual to s ee how
you c an find your trac ks . Figure 2 - 1 0 s hows a trac k log from a
G armin eTrex V is ta in the M apSourc e s oftware that c omes with
the unit. A s you c an s ee, eac h log inc ludes prec is e points along
the way and the time when the devic e was at eac h of thos e
points .

Figure 2-10. Viewing a GPS track log with time


and coordinates
A s you c an s ee, eac h log inc ludes prec is e points along the way
and the time the devic e was at that point.

You c an then view the E XI F data for the photos you took with a
program s uc h as E xifer (http://www.friedemann-
s c hmidt.c om/s oftware/exifer/), as s hown in Figure 2 - 1 1 , to s ee
exac tly when you took a partic ular photo.

Figure 2-11. Viewing the time a photo was taken


with Exifer
O nc e you have the time when a partic ular photo was taken, you
c an eas ily matc h it to your c oordinates at that s pec ific time.
T hen, s imply add your three geotags to the photo at Flic kr.

Mapping Your Photos

O nc e you have a number of your photos geotagged, you c an view


thos e photos on a map with a c ouple of different applic ations .
O ne quic k way to s ee your photos dis played on a G oogle M ap is
with an applic ation c alled Flyr, by P aul D owney (Flic kr member
ps d; http://www.flic kr.c om/photos /ps d/). Brows e to
http://flyr.whatfettle.c om and type your Flic kr us ername in the
field labeled "within this us er's photos ." C lic k the G oogle M aps
button, and you s hould s ee your geotagged photos appear on a
map, as s hown in Figure 2 - 1 2 .

Figure 2-12. Geotagged photos on a map with


Flyr
You c an us e the arrow buttons below the map to navigate
between your geotagged photos , or return to the main form to
s earc h for geotagged photos by others in your area.

A nother projec t, c alled G eobloggers


(http://www.geobloggers .c om), als o dis plays geotagged Flic kr
photos on a large G oogle M ap, and you c an find geotagged
photos taken around the world.

T his hac k has jus t s c ratc hed the geotagging s urfac e. I n the
future, as our c ell phones and c ameras bec ome loc ation- aware,
the proc es s of geotagging photos is bound to bec ome more
automated. U ntil then, a bit of manual gluing between c amera,
c oordinates , and Flic kr c an tie your photos to the loc ations
where they were taken.
Hack 13. Exploit Compound Tags

Compound tags make it easier to embed application-specif ic


data into photos.

M y friend L eo c reated a new group c alled O ne Word


(http://www.flic kr.c om/groups /one- word/), whic h c ollec ts photos
of s ingle words . T his is s imilar to the groups O ne L etter
(http://www.flic kr.c om/groups /oneletter/) and O ne D igit
(http://www.flic kr.c om/groups /onedigit/), whic h c ollec t photos of
individual letters and digits .

"H elp! " L eo wrote to me, "What is a good way to tag the photos
s o they c an be us ed for s c ripting purpos es ? "

L eo would like to enable people to make nic e rans om notes


[Hack #47] out of thes e photos , by identifying them with tags .
U nfortunately, s imply adding tags that matc h the words in the
photos is not enough.

Why not? C ons ider the problem here. L et's s ay L eo adds the
photo s hown in Figure 2 - 1 3 , of a graves tone c ontaining the word
PEACE, and tags the photo peace.

Figure 2-13. Leo's photo of a gravestone


T here are lots of other photos on Flic kr tagged with peace, and
finding the one of the graves tone is going to be nigh on
impos s ible unles s you plan to write s ome fanc y image-
rec ognition s oftware. A nd we really don't want to be was ting our
c omputer c yc les like that, do we?
"A ha! " you s ay, we c an c ollec t jus t the photos that are in the
O ne Word group, us ing group members hip as a filter. T his will
reduc e the lis t to jus t photos that c ontain words . O r, we c an add
an additional tag to the photo, word, whic h will identify it as
c ontaining a word.

C ertainly, we c an us e either of thes e filtering methods . H owever,


it is probable that many of thes e photos will have multiple tags .
C ons ider L eo's graves tone. I t c ontains the following tags :

leol30
word
cemetery
peace

With multiple tags , it's diffic ult to know whic h one repres ents the
ac tual word in the photo. D oes the graves tone s ay peace, or does
it s ay cemetery?

T he tric k to embedding applic ation- s pec ific data is to us e a


c ompound tag, s uc h as this :

oneword:peace

T he tag c ontains a unique prefix, oneword, whic h is unlikely to


c ollide with other tags . T he c olon s eparates the prefix from the
embedded tag c ontent.

U nfortunately, Flic kr does not c urrently do wildc ard matc hing on


tag s earc hes , s o retrieving the embedded data from s uc h a
c ompound tag is a little more time- c ons uming than doing a tag
s earc h, bec aus e we have to retrieve them individually for eac h
photo. T herefore, an additional grouping method, s uc h as
keeping the photos all in one group or us ing an additional
grouping tag, is s till needed.

T his hac k demons trates a P H P 4 s c ript that retrieves data from


photos with c ompound tags . You'll need to hos t it on a web
s erver.

I f you haven't us ed the Flic kr A P I before,


c hec k out the firs t few s ec tions of C hapter
6 . You might want to try s ome of the hac ks
in that c hapter before us ing this partic ular
s c ript.

What You'll Need

To us e the P H P s c ript, you'll need your own Flic kr A P I key. (See


[Hack #40] for information on how to get an A P I key.)

You'll als o need the phpFlic kr s c ripts [Hack #41] . T hes e s c ripts
als o make authentic ating other people a s nap, but you won't
need authentic ation for this hac k. You c an download thes e
s c ripts from http://www.phpflic kr.c om.

The Code

To retrieve all the "one- word" photos and their c orres ponding
words , this s c ript performs the following s teps :
1. D ownload the lis t of photos that are in the O ne Word
group.

2. For eac h photo, is s ue the flickr.photo.getInfo A P I


method, whic h will produc e XM L c ontaining the photo's
tags , among other information.

3. Walk through the tags and find the ones with the
matc hing prefix; then, extrac t the data us ing s tring
manipulation.

H ere's the P H P s c ript that performs thes e tas ks , produc ing a


lis t of photos from the O ne Word group and their embedded
words . I n your favorite text editor, c reate a file c alled
retrieveTags .php, and add the following c ode:

<?php
// retrieveTags.php
ini_set("error_reporting ", E_ALL);

// Configuration stuff
$flickrAPIKey = "your API key";
$cachingenabled = true;
$dbUser = "user"; //database user here
$dbPass = "pass"; //database password here
$dbAddress = "localhost"; //location of database
$dbTable = "table"; //location of table, will create one if it doe

// Create new phpFlickr object


require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey);
if ($cachingenabled == true)
{
$f->enableCache("db", "mysql://$dbUser:$dbPass@$dbAddress/$dbTab
}
// By default, we use the group_id of the One Word group
// You may pass in other group_ids as parameters
$group_id = '79664019@N00';
if (isset($_GET['group_id']))
$group_id = $_GET['group_id'];

$photos = $f->groups_pools_getPhotos($group_id);
?>

<html>
<head>
<title>retrieve tags</title>
</head>
<body>

<table><tr>

<?php
$n = 0;
foreach ($photos['photo'] as $photo) {
if ($n && $n % 6 == 0)
echo "</tr><tr>";

$photos_url = $f->urls_getUserPhotos($photo['owner']);

echo "<td><a href=$photos_url$photo[id]>";


echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "thumbnail") . ">";
echo "</a><br>";

$info = $f->photos_getInfo($photo['id'], $photo['secret']);


foreach ($info['tags']['tag'] as $tagn => $tag)
{
if (strncmp(strtolower($tag['raw']),'oneword:', 8) == 0)
{
$embeddedData = substr($tag['raw'], 8);
echo "$embeddedData</td>\n";
}
}
++$n;

?>
</td></tr></table>
</body>
</html>

Before uploading the s c ript, edit the following line to us e your


own A P I key:

$flickrAPIKey = "your API key";

T he phpFlickr wrapper has an optional c ac he feature. I f you wis h


to us e it, modify thes e lines to provide ac c es s information for a
databas e on your s erver:

$cachingenabled = true;
$dbUser = "user";//database user here
$dbPass = "pass";//database password here
$dbAddress = "localhost"; //location of database
$dbTable = "table";//location of table, will create one this is it
I f you do not wis h to us e c ac hing, turn it off by replac ing this
line:

$cachingenabled = true;

with this :

$cachingenabled = false;

Running the Hack

To run the hac k, upload the edited s c ript to your web s erver and
invoke it by typing its addres s into your web brows er:

http://www.yourwebsite.com/retrieveTags.php

You s hould s ee a lis t of photos from the O ne Word group, eac h


with its as s oc iated word, as s hown in Figure 2 - 1 4 .

Figure 2-14. Photos from the One Word group,


as displayed by retrieveTags.php
I f no words s how up beneath the photos , c hec k the photos to
make s ure they have been tagged c orrec tly.

C ompound tags are us ed for many of the more s ophis tic ated
applic ations on Flic kr. O ne of the more well- known us es is
geotagging [Hack #12] . L ongitude and latitude c oordinates are
attac hed to photos us ing the tags geo:lon=longitude and
geo:lat=latitude, res pec tively. Sinc e thes e photos are not all
c ontained in a group pool, the additional grouping tag geotagged
is als o applied to eac h geotagged photo, s o that they c an be
c ollec ted us ing a s imple tag s earc h.

See Also
[Hack #40]

[Hack #41]

[Hack #47]

[Hack #12]
Hack 14. Make a Flickr-Style Tag Cloud

A dding a tag cloud to your web site is easier than getting a bad
haircut!

I f the illus trations in thes e next few pages look familiar, you've
s een tag c louds before. Tag clouds are c lus ters of tags rendered
with differently s ized fonts to indic ate the relative popularity of
the tags in a datas et. C lic k on any of the tags to retrieve data
matc hing that tag (s uc h as photos ).

Flic kr us ed tag c louds firs t, followed by other Web 2 .0 s ites s uc h


as Tec hnorati. N ow, tag c louds s eem to be ubiquitous , appearing
on nearly every new web s ite that wants to join the Web 2 .0
party. P erhaps that's why J effrey Zeldman proc laimed tag c louds
"the new mullets ."

Fortunately for thos e of us who are s till mulletles s , D an


Steingart has written a s c ript that makes a tag c loud from the
tags as s oc iated with your Flic kr photos . T he s c ript is nearly
ready to go and requires jus t a few minor modific ations .

What You'll Need

To us e D an's s c ript, you'll need your own Flic kr A P I key [Hack


#40] .

You'll als o need the phpFlic kr s c ripts [Hack #41] (whic h als o
make authentic ating other people a s nap, although you won't
need authentic ation for this hac k). You c an download thes e
s c ripts from http://www.phpflic kr.c om.

To get s tarted, ins tall the phpFlickr s c ripts on your web s ite, as
des c ribed in [Hack #41] . T hen download and unpac k D an
Steingart's c loudTagFlic kr s c ript, whic h is available from
http://www.allthings alc es te.c om/c loudtagflic krphp/.

The Code

I n the cloudTagFlickr.php s c ript, edit the following two lines to


us e your own us ername and A P I key:

$username = "flickruser"; //flickr user name here


$flickrapikey = "flickrapikey"; //key in here

T he phpFlickr wrapper has an optional c ac he feature. I f you want


to us e it, modify thes e lines to provide ac c es s information for a
databas e on your s erver:

$cachingenabled = true;
$dbUser = "user"; //database user here
$dbPass = "pass"; //database password here
$dbAddress = "localhost"; //location of database
$dbTable = "table"; //location of table, will create one if it doe

I f you do not want to us e c ac hing, turn it off by replac ing this


line:
$cachingenabled = true;

with this :

$cachingenabled = false;

N ow, prepare a s ec ond file that makes us e of cloudTagFlickr.php


as part of a more c omplex web page. C all the file
tes tCloudTag.php and add the following c ode:

<? require_once("phpFlickr/phpFlickr.php"); ?>

<html>
<head></head>
<body>

This is a tag cloud.

<center><table width=50%><tr><td>

<? include "cloudTagFlickr.php"; ?>

</td></tr></table></center>

That was a tag cloud.

</body>
U pload both files (cloudTagFlickr.php and tes tCloudTag.php) to
your web s erver.

Running the Hack

Firs t we'll tes t jus t the c loudTagFlic kr s c ript, to make s ure


everything is c opas etic . I nvoke the s c ript by typing its addres s
into your brows er:

http://www.yourwebsite.com/cloudTagFlickr.php

I f all is right with the world and your karma, you s hould s ee
s omething like Figure 2 - 1 5 .

Figure 2-15. Testing cloudTagFlickr.php


I f you have problems , you might need to turn on P H P error
reporting to allow you to s ee what's going on. I would s ugges t
turning off the c ac hing feature firs t and getting it working without
c ac hing, s inc e that's s impler.

O nc e you get it working, try the s ec ond s c ript, whic h inc ludes
the tag c loud as part of a more c omplex web page:

http://www.yourwebsite.com/testTagCloud.php

T he res ult looks s omething like Figure 2 - 1 6 .

Figure 2-16. Testing testTagCloud.php


For both of thes e s c ripts , you c an pas s a few options to modify
the appearanc e of the tag c loud. H ere are a few examples :
You c an s pec ify the name of s ome other us er, like my
friend Spec ial:

http://www.yourwebsite.com/testTagCloud.php?name=special

You c an us e the minsize and maxsize parameters to


s pec ify the range of font s izes :

http://www.yourwebsite.com/testTagCloud.php?minsize=10&maxsize=64

By default, the tags are s orted alphabetic ally by tag


name, but you c an als o get a random s ort:

http://www.yourwebsite.com/testTagCloud.php?sort=random

or an as c ending s ort by s ize, whic h looks nic e:

http://www.yourwebsite.com/testTagCloud.php?sort=asc
or a des c ending s ort by s ize, whic h looks even nic er
(Figure 2 - 1 7 ):

Figure 2-17. Tag cloud with descending sort


http://www.yourwebsite.com/testTagCloud.php?sort=desc

D an has als o added s ome nic e c oloring options , s uc h as


grays c ale:

http://www.yourwebsite.com/testTagCloud.php?color=greyscale

and a hot/c old c olor gradient:

http://www.yourwebsite.com/testTagCloud.php?color=hotcold

Figure 2 - 1 8 s hows a final c loud tag with a random s ort and


hot/c old c oloring.

Figure 2-18. Tag cloud with random sort and


hot/cold coloring
M ore rec ently, D an has added a new option, threshold, that
allows you to filter for more c ommon tags . For folks who have
pos ted enormous numbers of photos , this makes the tag c louds
muc h more manageable.

Figure 2 - 1 9 s hows an example us ing Fubuki's rather large


photos tream, whic h c ontains far too many tags to be s hown
without a tag thres hold:

Figure 2-19. Essence of Fubuki, tags matching


over 40 photos
http://www.yourwebsite.com/testTagCloud.php?name=fubuki&threshold=

N ow that's a pithy tag c loud!

See Also

[Hack #40]

[Hack #41]
Chapter 3. Viewing Photos

H ac ks 1 5 - 2 3

H ac k 1 5 . A dd Flic kr Searc h to Firefox

H ac k 1 6 . Find P ic tures You C an Reus e L egally

H ac k 1 7 . Subs c ribe to Flic kr

H ac k 1 8 . Rate P hotos

H ac k 1 9 . Travel with Flic kr

H ac k 2 0 . Build a C us tom Flic kr Feed

H ac k 2 1 . Set Random D es ktop Bac kgrounds

H ac k 2 2 . Build a Flic kr Sc reens aver

H ac k 2 3 . V iew Flic kr P hotos on T iVo


Hacks 15-23
O ne of the mos t fun as pec ts of us ing Flic kr is dis c overing
amazing photographs . C lic king through the pages of Flic kr is like
walking through an enormous public gallery where anyone c an
hang a photo and have a c onvers ation about that photo with
s omeone els e. You'll find s everal ways to view photos on Flic kr,
and getting to know the bas ic page layouts will help you navigate
this gallery and find photos that you c onnec t with.

O ne bas ic page you'll enc ounter frequently is a Flic kr


photos tream. A photos tream is all of the photos that belong to a
s pec ific photographer, dis played in order from newes t to oldes t.
For example, Figure 3 - 1 s hows a Flic kr photos tream for one of
the authors of this book, with the mos t rec ently added photo at
the top and the res t following in revers e- c hronologic al order.

Figure 3-1. Flickr photostream


From the photos tream page, you c an navigate to other Flic kr
areas related to a partic ular photographer. C lic king the P rofile
link will reveal more information about the photographer; the
Favorites link will s how you photographs by other members that
this us er has marked as favorites , and the Sets link will s how
you all of the photographer's groups of photographs .

C lic king a photo in the photos tream will take you to a larger
vers ion of the photograph on a photo detail page, as s hown in
Figure 3 - 2 .

Figure 3-2. Flickr photo detail page


You c an end up at a photo detail page from many loc ations
ac ros s Flic kr, and it's probably where you'll s pend mos t of your
time at Flic kr. From the photo detail page, you c an find all of the
information related to a photo, inc luding the title, des c ription,
tags , c opyright details , date taken, and number of times the
photo has been viewed. You'll als o be able to s ee whic h photo
s ets the photo belongs to, whic h groups the photo has been
added to, and a link to the photographer's photos tream. A ny
c omments related to the photo will be dis played below the
des c ription on the photo detail page.

Sets are another important type of page at Flic kr. Sets are groups
of photographs that a photographer has put together for eas y
viewing. Figure 3 - 3 s hows a s et c alled "L ittle P ups " by one of
the authors .

Figure 3-3. Flickr set page


A s et c an be us ed to dis play a group of photos often around a
s pec ific themeeven if they weren't all uploaded at the s ame time.

T his c hapter will take you beyond the bas ic s of Flic kr photo
viewing, into more advanc ed ways of enjoying photos available
at Flic kr. From integrating Flic kr photo s earc h with your brows er
[Hack #15] to us ing Flic kr photos as a s c reens aver [Hack #22],
you'll find ways to c onnec t with photos you might not have found
by s imply wandering the gallery.
Hack 15. Add Flickr Search to Firefox

To f ind photos quickly at Flickr, you can add a Flickr option to


your Firef ox quick search box.

I f you us e the Firefox web brows er


(http://www.mozilla.org/produc ts /firefox/), you're probably
already aware of the us eful s earc h box in the upper- right c orner.
From any page, at any time, you c an s imply type a s earc h term
into the box and pres s E nter, and the res ults page will c ome up in
the brows er.

T hough G oogle is the default s earc h engine, you c an c lic k the


arrow to c hoos e another s earc h engine via the s earc h box's
handy drop- down menu, as s hown in Figure 3 - 4 .

Figure 3-4. Firefox quick search options


T he nic e thing about this lis t of potential s earc h engines is that
you c an add any s earc h engine of your c hoic e. I n the drop- down
lis t is an A dd E ngines ... option that takes you to a page with
more s earc h c hoic es , whic h you c an ins tall with a few c lic ks . T he
N ew Searc h E ngines s ec tion of the M ozilla s ite c ontains a page
with s even different Flic kr- related s earc hes you c an add to the
Firefox s earc h box (M ozilla is the tec hnology behind Firefox).
T hes e s earc hes are primarily for s earc hing through Flic kr
forums , groups , and tags .

To add a Flic kr s earc h engine, s imply go to


http://myc roft.mozdev.org/download.html? name=Flic kr and c lic k
the name of the s earc h engine you'd like to add. A pop- up box
will as k you to c onfirm your c hoic e; c lic k O K, and the new c hoic e
will be available in the Firefox s earc h box menu. Behind the
s c enes , Firefox has c opied a s mall .s rc file and ic on to the
s earchplugins direc tory of the Firefox ins tallation. T his text file
defines how the s earc h works .

I f you don't find the perfec t Flic kr s earc h at the M ozilla page, it's
fairly eas y to build your own s pec ialty Flic kr s earc h and add it to
your lis t of available s earc h engines . T his hac k s hows you how.

Flickr Search

To s earc h for photos at Flic kr by a s pec ific tag, a s et of tags , or


words in the titles and des c riptions , brows e to the Flic kr Searc h
page (http://www.flic kr.c om/photos /s earc h/). E nter s ome words
into the tags field or the titles , tags , and des c riptions field, and
c lic k Searc h. You'll s ee res ults like the ones s hown in Figure 3 -
5.

Figure 3-5. Flickr photo search


To integrate this s earc h into the brows er, you'll firs t need to note
the U RL . A s earc h for photos with the tags needle or hays tack has
this U RL :

http://www.flickr.com/photos/search/tags:needle%2Chaystack/tagmode

N otic e that the tags are s eparated by the s ymbol %2C, the U RL-
enc oded vers ion of a c omma. tagmode:any lets the s earc h know
you want to matc h any of the tags mentioned ins tead of all of the
tags mentioned. A rmed with this knowledge, you c an put
together your own Firefox quic k s earc h.

The Code

Bec aus e Flic kr s earc h res ult U RL s are formatted a bit differently
from the res ult U RL s of many other s earc h engines , the Firefox
quic k s earc h format c an't s end queries to Flic kr direc tly. But
that s houldn't s top a Flic kr hac ker from adding a quic k s earc h
entry. A bit of J avaSc ript c an do s ome trans lating, but for that
you'll need a quic k Flic kr s earc h proxy s c ript.

C reate a text file c alled flickr-s earch.htm and add the following
c ode:

<html>
<head>
<title>Flickr Proxy</title>
</head>

<body>
<script language="JavaScript" type="text/javascript">
// Find the tags
var esign = document.URL.lastIndexOf('=');
var tags = document.URL.substring(esign+1);

// Convert spaces to URL-encoded commas


tags = tags.replace(/%20/g,"%2C");
tags = tags.replace(/\+/g,"%2C");

// Build the search results URL at Flickr


var action = "http://www.flickr.com/photos/search/";
var query = "tags:"+tags+"/tagmode:any/";

// Send the user to Flickr with the formatted URL


document.location = action + query;
</script>
</body>
</html>

T his c ode grabs the inc oming query from a Firefox s earc h and
formats a proper s earc h res pons e U RL for Flic kr. Spac es in the
s earc h are trans formed into c ommas , jus t as they are on Flic kr,
and the s earc h mode (matc h any or all tags ) is s et here as well.

N ote that the variable query holds the tags c oming in on the
c ommand line and the s earc h mode, tagmode:any. You c an c hange
tags: to text: if you'd rather s earc h titles , des c riptions , and tags ,
but if you do, be s ure to als o c hange the mode to one of the text
options : s pec ify sort:relevance or sort:interesting, or leave out
the sort option to s ort by mos t rec ent.

U pload flickr-s earch.htm to a public ly available web s erver and


note the U RL , whic h s hould look s omething like this :
http://www.example.com/flickr-search.htm

N ow that you have a quic k Flic kr- U RL proxy s et up, you c an


write the file that will tell Firefox where to s end s earc h reques ts .
C reate a file c alled flickr-tags .s rc in a text editor s uc h as
N otepad and add the following c ode:

# Flickr Tag Search


#
# Created September 17, 2005

<SEARCH
version="7.1"
name="Flickr Tags Search"
description="Search for photos by tag at Flickr!"
method="GET"
action="http://www.example.com/flickr-search.htm" >

<input name="q" user>

</search>

A s you c an s ee, this file begins with an opening <SEARCH> tag that
holds the name of the s earc h and a brief des c ription. Be s ure to
point the action attribute to your Flic kr proxy U RL . T he <input>
tag lets Firefox know that the value s hould c ome from us er input,
and that it s hould be added to the ac tion U RL .

Running the Hack


Save flickr-tags .s rc and add it to the Firefox s earchplugins
direc tory (on Windows , us ually loc ated at C:\Program Files \Mozilla
Firefox\s earchplugins \). When you res tart Firefox, you'll find a new
option in the s earc h lis t c alled Flic kr Tags Searc h. C hoos e this
option, and type a query s uc h as needle haystack in the s earc h
box. I f all goes well, you s hould s ee the s ame page of images
s hown in Figure 3 - 5 .

To go the extra mile, you'll want to c reate a Flic kr ic on to


ac c ompany the s earc h engine in the drop- down lis t. A good
c andidate is the Flic kr favic on, available at
http://www.flic kr.c om/favic on.ic o. C opy the ic on to your des ktop,
and trans form it into a G I F or P N G file. (You c an us e the I C O
plug- in for P hotos hop, available at
http://www.telegraphic s .c om.au/s w/.)

N ame the file flickr-tags .gif or flickr-tags .png, and c opy it to the
s earchplugins direc tory. T he next time you s tart Firefox, you
s hould s ee the Flic kr ic on next to the new s earc h engine.

By taking s ome time to examine the different s earc h options at


Flic kr you c an us ually find a way to integrate thos e s earc hes
into Firefox, giving you quic k ac c es s to information you us e
frequently.
Hack 16. Find Pictures You Can Reuse
Legally

Use the Flickr Creative Commons tools to f ind photos with


special licenses or let others know how they can use your
photographs.

M os t of the photos you s ee at Flic kr are c opyrighted. T he default


lic ens e s etting at Flic kr is a s tandard c opyright, whic h means
the original photographer c ontrols how the photo c an be us ed.
U nfortunately, you c an never be s ure how a partic ular
photographer will reac t if you us e part or all of her work in your
own projec t.

Say you're preparing a public pres entation and you'd like to us e


a photo of the L iberty Bell to illus trate a point. U nles s you
s pec ific ally obtain permis s ion (and pos s ibly pay a fee), you c an't
be s ure the c reator of a photo you find on the Web won't s ue you
for c opyright violation. While there is a legal term c alled fair us e
that protec ts s ome us e of c opyrighted materials es pec ially for
educ ational purpos es it's hard to know exac tly what us es fall
under this legal definition, bec aus e the c onc ept of fair us e is
only vaguely defined. Without c ontac ting the photographer or
owner of the c opyright, there's no way to know what they'll
c ons ider a fair us e of their materials .

T his legal ambiguity is one of the reas ons that the nonprofit
group C reative C ommons (C C ) has made s everal alternative
lic ens es available to artis ts who want to lic ens e their work in
more s pec ific ways than a general c opyright provides . For
example, you c an make your work available to anyone who wants
to us e your photos on the c ondition that they're us ed for
nonc ommerc ial purpos es , but you c an s till require payment for
any c ommerc ial us e. T his means s omeone c an freely us e one of
your photos lic ens ed in this way for, s ay, a s c hool report, but
he'd need to pay you for your photo if you he were c ompiling a
book he intended to s ell. With a C reative C ommons lic ens e,
everyone knows exac tly how you would like your work to be
us edor not us ed.

U s ing photos under a C C lic ens e is jus t as eas y as s haring


them. O ne c ompelling as pec t is that as long as you're following
the c onditions s et forth in the lic ens e, you don't need to pay a
photographer to us e her workor even c ontac t her to as k
permis s ion. I f for any reas on you'd like to us e the work in a way
that's not c overed by the lic ens e, however, you'll need to get in
touc h with the photographer. Bas ic ally, you jus t need to know
how the C reative C ommons lic ens es work to make s ure you're
playing by the rules .

Understanding CC Licenses

C reative C ommons offers four primary c onditions in its lic ens es ,


in different c ombinations :

Attribution

N o matter how you us e the work, you mus t give the


author c redit. A ll lic ens es inc lude this c ondition.
No Derivatives (NoDerivs )

You c an us e only exac t c opies of the work in its entirety,


not piec es of the work arranged in a different way.

Non-Commercial

T he work c an be us ed for a nonc ommerc ial projec t only.

Share Alike

You c an us e the work as long as your work is lic ens ed in


the s ame way.

H ere are the s ix lic ens es offered:

A ttribution

A ttribution- N oD erivs

A ttribution- N onC ommeric al- N oD erivs

A ttribution- N onC ommerc ial

A ttribution- N onC ommerc ial- ShareA like

A ttribution- ShareA like


So, if you s pot a photograph of the L iberty Bell with an
Attribution-NoDerivs C reative C ommons lic ens e on Flic kr, you
know that the photographer has made the photo available to
anyone who wants to us e it for any purpos e, provided that c redit
is given and that the photo is us ed in its entirety, rather than
being c ropped or blended with other images .

T he other lic ens es work in a s imilar way. O nc e you know the four
c onditions , you c an quic kly determine how the photographer
would like you to us e her work by looking at the lic ens e.

Licensing Your Photos

By default, any images you upload to Flic kr will be under the


s tandard c opyright lic ens e. H owever, you c an s witc h any P ublic
image to a C reative C ommons lic ens e at any time.

To apply a lic ens e to a photo, brows e to the photo's detail page


and note the c opyright s tatement"A ll rights res erved"under the
A dditional I nformation heading to the right of the photo. C lic k
the "s et privac y" link, and you'll be taken to the "P rivac y and
c ontrol" page [Hack #2] for that photo. O n the lower- left s ide of
the page, c lic k the "A dd a lic ens e for your photo" link to bring up
the L ic ens e page, s hown in Figure 3 - 6 .

Figure 3-6. Flickr License page for a single


image
C hoos e the lic ens e you'd like to us e for the image, and c lic k
Save L ic ens e. O nc e you've s et the lic ens e, others will be able to
tell whic h lic ens e you've s elec ted by looking at the new
c opyright s tatement"Some rights res erved"under A dditional
I nformation, as s hown in Figure 3 - 7 .

Figure 3-7. Creative Commons license on a


photo detail page
I f you c lic k the "c c " logo, you'll go direc tly to the lic ens e page
for that photo, where you c an s witc h to a different C reative
C ommons lic ens e or bac k to the traditional c opyright. O ther
viewers who c lic k the "c c " logo on your photo's detail page will
be taken to the C reative C ommons page for that partic ular
lic ens e, whic h explains how the photo c an legally be us ed. Figure
3 - 8 s hows the Attribution-NoDerivs lic ens e page at C reative
C ommons .

Figure 3-8. The Attribution-NoDerivs license


explanation
I f you'd like to make all of your photos available under a
partic ular C reative C ommons lic ens e, you c an s et a global
lic ens ing preferenc e. U nder Your A c c ount at the bottom of any
Flic kr page, c lic k the "A c c ount page" link. From your ac c ount
page, c lic k P hoto L ic ens ing under the P hoto Settings heading.
You'll find more information about C reative C ommons lic ens ing
on this page, and a form that will let you s et a default lic ens e for
any photos you add to Flic kr.

Finding CC-Licensed Content

A s you brows e photos on Flic kr, you're bound to run into s ome of
the thous ands of images that are C C - lic ens ed. Keep your eye
out for the C reative C ommons logo on photo detail pages .

I f you're s pec ific ally looking for photos you c an us e in your own
projec ts , brows e to the Flic kr C reative C ommons page
(http://www.flic kr.c om/c reativec ommons /). You'll find rec ently
added photos lis ted by lic ens e type, as s hown in Figure 3 - 9 .

Figure 3-9. Flickr Creative Commons page


To s earc h for images with a c ertain lic ens e, c lic k the "See more"
link under any of the lic ens e headings . From there, you c an us e
the s earc h form at the top of the page to find s pec ific images
under that partic ular lic ens e.

So, the next time you're looking for s upporting text or


photographs , you c an us e the Flic kr C reative C ommons s earc h
to find s omething appropriate, s uc h as the photograph of the
L iberty Bell in Figure 3 - 1 0 by Flic kr member rdes ai
(http://www.flic kr.c om/people/pic drop/).

Figure 3-10. CC-licensed image of the Liberty


Bell
rdes ai publis hed the photo under an Attribution lic ens e, whic h
means this member s imply wants c redit in exc hange for us e of
the photo. Targeting C C - lic ens ed material takes the ambiguity
out of the s tandard c opyright s ys tem and lets you know how you
c an us e s ome of the photos you find on Flic kr.
Hack 17. Subscribe to Flickr

Flickr of f ers RSS and A tom news f eeds of much of its data,
making it easy to keep track of your f avorite people, groups,
and tags.

N ews feeds have revolutionized the way people read s ites on the
Web. I ns tead of brows ing hundreds of pages ac ros s the Web
every day, you c an us e s oftware c alled news readers to s ubs c ribe
to news feeds and dis play any new information in a friendly,
c ons is tent format.

T he folks at Flic kr have rec ognized the demand for news feeds
and have made mos t of the data you s ee on the web s ite
available in a number of different feeds . For example, if you want
to trac k a partic ular photographer, you c an add that pers on's
photos tream feed to your news reader and s ee any new photos he
pos ts without ever vis iting Flic kr.

T he firs t s tep to s ubs c ribing to a Flic kr feed is finding a feed U RL


that you c an c opy and pas te into a news reader. You c an s pot
news feeds on Flic kr by looking at the bottom of the page for feed
options like the ones s hown in Figure 3 - 1 1 .

Figure 3-11. The feed options found at the


bottom of many Flickr pages
N ews feeds are s truc tured XM L doc uments intended to be read
by mac hines rather than humans . Flic kr offers feeds in both RSS
(Really Simple Syndic ation) and A tom formats ; you won't notic e
a differenc e between the two, and you c an us e either format in
mos t news readers . To c opy a feed U RL , right- c lic k (C ommand-
c lic k on a M ac ) on either the RSS 2 .0 link or the A tom link and
c hoos e C opy L ink L oc ation from the menu. T he feed U RL will
then be available on your virtual c lipboard.

I n addition to links to the feed U RL s , you'll notic e an "A dd to M y


Yahoo! " button that lets you automatic ally add the feed to
Yahoo! 's news portal (available at http://my.yahoo.c om). C lic k
the button to add that partic ular feed to M y Yahoo!

Flickr Feeds

By far, the eas ies t way to add a feed to your news reader is by
c opying the U RL from the bottom of a Flic kr page. I f you pay
attention to the feed U RL s , though, you may be able to c ons truc t
your own Flic kr feed U RL s in les s time than it would take to
brows e to the appropriate pages and c opy the links .

E very feed U RL s tarts with the bas e www.flickr.com domain. From


there, the feeds vary widely, but they s tandardize again at the
end of the feed with the format attribute. T he format c an be s et to
rss_200, indic ating the RSS 2 .0 format, or atom_03, if you'd rather
us e the A tom 0 .3 format. C hanging the format s etting of a U RL
c hanges the format of the feed.

A nother important c omponent of many Flic kr feeds is an internal


I D c alled an NSI D. E very member and group on Flic kr has an
internal alphanumeric I D that repres ents that partic ular entity in
the Flic kr databas e. M any feed U RL s us e the N SI D . I f you're
examining a feed U RL and s ee a group of 1 2 to 1 5 c harac ters
that c ontains an @ s ymbol, you know you're looking at a Flic kr
N SI D .

You c an often c hange the c ontents of the feed by tweaking the


attributes in the U RL , either by s wapping out N SI D s or c hanging
the format attribute. H ere's a look at the feeds available at Flic kr,
along with the U RL format for eac h type of feed.

Members

To s ee every new public photo by a partic ular photographer at


Flic kr, you c an s ubs c ribe to her photos tream. T he photos tream
feed U RL requires a member N SI D and looks like this :

http://www.flickr.com/services/feeds/photos_public.gne?id=insert m

You c an find the N SI D for any partic ular member (inc luding
yours elf) with jus t a little bit of works ee [Hack #24] for details .

You c an als o keep tabs on your c ontac ts ' photos with a Flic kr
feed. I f you'd rather s ee photos from your c ontac ts in your
news reader ins tead of going to your c ontac ts page
(http://www.flic kr.c om/photos /friends /), you c an s ubs c ribe to a
U RL of the following format:

http://www.flickr.com/services/feeds/photos_friends.gne?user_id=in

To keep trac k of c omments people are pos ting about your


photos , s ubs c ribe to the rec ent c omments feed:

http://www.flickr.com/recent_comments_feed.gne?id=insert your NSID

Subs tituting your c ontac ts ' N SI D s in a U RL of this format


provides even more trac king fun.

Groups

Flic kr groups give members a c hanc e to c ongregate and dis c us s


and s hare photos . T here are two types of feeds as s oc iated with
groups . T he firs t feed is the dis c us s ion as s oc iated with the
group. T he dis c us s ion feed c ontains all new pos ts and replies to
pos ts . I ts U RL has the following format:

http://www.flickr.com/groups_feed.gne?id=insert group NSID&format=

O ne eas y way to get the N SI D for a partic ular group is to c opy


the N SI D from a feed link at the bottom of the group home page.
O f c ours e, if you have the feed U RL , you don't need to worry
about finding the N SI D to build your own!

You c an s ubs c ribe to the group photo pool for any given group
with a U RL like the following:

http://www.flickr.com/groups/insert group URL name/pool/feed/?form

N otic e that ins tead of the group N SI D , the photo pool feed us es
the group name. You c an find the group U RL name by examining
the U RL of the group home page. For example, the Flic kr H ac ks
group is available at:

http://www.flickr.com/groups/flickrhacks/

You'll find the group name (in this c as e, flickrhacks) at the end of
the U RL , after /groups/.

Tags

To s ubs c ribe to all photos tagged with a partic ular keyword, you
c an us e the following U RL format:

http://www.flickr.com/services/feeds/photos_public.gne?tags=insert

I magine you're interes ted in photos of the moon and you want to
keep trac k of any photos that flow through Flic kr that are tagged
with moon. You c an s imply ins ert the tag and s ubs c ribe to the
feed, and you won't mis s any new photos .

To s ubs c ribe to multiple tags in the s ame feed, s eparate the


tags with c ommas . For example, if you want to s ee pic tures of
both the moon and the s un, you c ould build the following U RL :

http://www.flickr.com/services/feeds/photos_public.gne?tags=moon,s

N ote that multiple tags are an OR matc h, meaning the feed will
s how photos tagged with moon or s un. U nfortunately, Flic kr
does n't offer AND matc hes in this feed, but you c an always build
your own feed [Hack #20] with the A P I .

Flickr news

While not direc tly related to Flic kr photos and dis c us s ion, you
c an als o s ubs c ribe to news s ourc es about Flic kr its elf. You'll find
RSS feeds for the Flic kr Blog
(http://feeds .feedburner.c om/Flic krblog/), the Flic kr H elp Forums
(http://www.flic kr.c om/forums /help/feed/? format=rs s _2 0 0 ), and
the Flic kr N ews and D evelopment C hange L og
(http://flic kr.c om/news _feed.gne?
dev=1 &news =1 &format=rs s _2 0 0 ).

Reading Feeds
I f you don't already have a favorite news reader, you'll need to
c hoos e one before you c an s ubs c ribe to Flic kr feeds . A
news reader c an be an applic ation you download or a web s ite you
vis it. H ere's a look at s ome popular news readers and how they
work with Flic kr feeds .

My Yahoo!

M y Yahoo! (http://my.yahoo.c om) is one of the mos t widely us ed


news readers , though you might not even know it's a news reader.
You c an add any RSS feed to M y Yahoo! by c lic king the A dd
C ontent link at the top of the page. From the A dd C ontent page,
c lic k the "A dd RSS by U RL " link next to the Find button. P as te
the feed U RL into the form and c lic k A dd. Figure 3 - 1 2 s hows how
feed for a photographer's photos tream looks at M y Yahoo!

Figure 3-12. Flickr photo feed at My Yahoo!


T he Flic kr photo feed will be added to the narrow c olumn of M y
Yahoo! c ontent on the s ide of the page. You c an navigate
between the five lates t photos from the photographer us ing the
arrow keys in the upper- right c orner of the box. A lternately, you
c an c lic k the Show A ll... link to s ee all five photos at onc e, as
s hown in Figure 3 - 1 3 .

Figure 3-13. Showing all photos in a feed at My


Yahoo!
A s you c an s ee, the photos are s maller, but you c an s ee them all
at a glanc e. You c an c lic k the edit button in the upper- right
c orner to c hange the number of photos you s ee, or c lic k any of
the photos to go direc tly to that photo's detail page at Flic kr.

Bloglines

Bloglines (http://www.bloglines .c om) is a free web- bas ed


news reader. To add feeds , c lic k the A dd link at the top of the M y
Feeds page. From the Subs c ribe page, pas te in the U RL , c lic k
Subs c ribe, and follow the prompts for adding a feed. O nc e the
feed is added, you'll find it in your feed lis t on the left s ide of the
page, as s hown in Figure 3 - 1 4 .

Figure 3-14. Flickr tag feed at Bloglines


Bloglines will s how the title of the photo, a thumbnail, the
des c ription, and the Flic kr member name of the pers on who
pos ted the photo. You c an c lic k the photo or title to brows e to
that photo's detail page at Flic kr.

NetNewsWire

M ac us ers c an ins tall and download a news reader c alled


N etN ews Wire (http://www.ranc hero.c om/netnews wire/). A free
3 0 - day trial vers ion is available, but at the time of this writing if
you want to keep it pas t that it will c os t you $ 2 4 .9 5 . To add a
feed in N etN ews Wire, c lic k Subs c ribe and pas te in the feed.
You'll find a link to the feed in the left pane, as s hown in Figure
3 -1 5 .

Figure 3-15. Flickr tag feed in NetNewsWire


E ntries in the feed are s hown at the top right, and the entry
details are s hown in the bottom- right pane. N etN ews Wire s hows
Flic kr photos along with titles , des c riptions , and member names .

Email and browser solutions

N ews feeds are being baked into the fabric of many applic ations ,
and you might be able to s ubs c ribe to Flic kr feeds from within
your favorite web brows er or email c lient. For example, the
Firefox web brows er (http://www.mozilla.org/produc ts /firefox/)
s upports L ive Bookmarks . A s you brows e around Flic kr with
Firefox, look for an orange L ive Bookmarks ic on in the lower-
right c orner of the brows er window. C lic k the ic on to s ee your
s ubs c ription options . O nc e s ubs c ribed, you'll s ee the titles of
new pos ts or photos in your Bookmarks menu.

O utlook us ers might want to try the N ews gator


(http://www.news gator.c om) plug- in, whic h lets you view news
feeds as you would inc oming email mes s ages . T hunderbird
(http://www.mozilla.org/produc ts /thunderbird/) us ers have RSS
s ubs c riptions built in, but at the time of this writing, there's no
H T M L s upport, s o you won't s ee Flic kr photos .

Beyond the Basics

Flic kr feeds don't c over every c onc eivable c ombination of data


available at Flic kr, but you c an keep trac k of the mos t c ommon
bits through the built- in feeds . H owever, if there's s ome piec e of
data you want to trac k in your news reader that is n't immediately
available in a feed, c hanc es are good that you c an roll your own
feed [Hack #20] with the Flic kr A P I . O nc e you're s ubs c ribed to
the relevant Flic kr feeds , you may never have to vis it the s ite
again!

See Also

[Hack #20]
Hack 18. Rate Photos

A n independent application called f lickRate adds a rating


system to Flickr, allowing you to judge which photos are f unny,
original, or beautif ul.

A puzzling as pec t of Flic kr is that there's no way to rate the


photographs you s ee. A mazon lets you rate any of its produc ts ,
eBay lets you rate s ellers , N etflix lets you rate movies , and
there are hundreds of other s ites that let you us e a s tar or other
rating s ys tem to voic e your opinion about produc ts on offer or
elements of the s ite.

Flic kr's c reators have dis tinc tly c hos en not to inc lude
ratings pos s ibly to avoid turning it into a c ompetition. E very
photo has value to s omeone, and they might have felt that a
ratings s ys tem was n't the atmos phere they wanted to provide.
I ns tead of ratings , Flic kr provides a way for you to mark c ertain
photographs you s ee as "favorites ."

A bove any photo on the photo detail page, you'll find a button
that s ays "A dd to Favorites ." C lic k the button, and you'll
es s entially bookmark that pic ture s o that you c an view it
anytime in the future. To s ee all of your favorites on one page, as
s hown in Figure 3 - 1 6 , c lic k the "Your favorites " link on your
Flic kr home page.

Figure 3-16. Flickr favorites page


E ven though thous ands of Flic kr us ers are adding favorites day
in and day out, there's no way to s ee global patterns to ans wer
this ques tion: "Whic h photos ac ros s Flic kr are mos t often added
as favorites ? "

J us t bec aus e Flic kr does n't offer ratings does n't mean that you
c an't take part in a ratings s ys tem, though. A n applic ation c alled
flic kRate by N ic olas H oizey lives a parallel life alongs ide Flic kr
and gives Flic kr us ers a way to rate the photos they s ee.
flic kRate als o gives you a look at the highes t- rated photos ,
determined by people us ing flic kRate.

Rating Photos

flic kRate lets you rate photos bas ed on three c riteria:


A es thetic s , O riginality, and Fun. I ns tead of giving a photo a
s imple s tar rating, you rate bas ed on thes e three c riteria on a
s c ale of 1 to 7 . I f you think a photo is beautiful but lac ks
originality or a s ens e of fun, you c ould rate it high for A es thetic s ,
but low for O riginality and Fun. Similarly, a photo that's very
funny and unique might not be all that attrac tive. I n this c as e,
you c ould give high marks for Fun and O riginality, but low marks
for A es thetic s .

To s tart rating photos , you'll need a free flic kRate ac c ount.


Brows e to the flic kRate s ite (http://flic krate.gas teropod.c om)
and enter your email addres s and a pas s word for your ac c ount in
the form on the right s ide of the page. Figure 3 - 1 7 s hows the
flic kRate home page at the time of this writing.

Figure 3-17. The flickRate home page


You'll need to validate your ac c ount by following a link s ent to
your email addres s , and then you'll jus t need one of the flic kRate
tools available on the s ite. T hes e flic kRate tools let you brows e
the Flic kr s ite as you normally would, but they put the rating
features c los e at hand s o that you c an rate any photos you s ee.
To ins tall one of the tools , c lic k the Tools link at the top of the
flic kRate home page to brows e to the tools page.

A s imple option that will work for any brows er is the "flic kRate
this ! " bookmarklet. D rag the "flic kRate this ! " link to the links
toolbar on your brows er to ins tall the bookmarklet. T hen, c lic k
the bookmarklet from any Flic kr photo detail page to open a
flic kRate pop- up window like the one s hown in Figure 3 - 1 8 . I n
the new window, c hoos e your ratings and c lic k Rate, and your
ratings will be s aved at the flic kRate web s ite.

Figure 3-18. flickRate bookmarklet window


Bec aus e many brows ers bloc k pop- up
windows (Firefox does by default), you
might need to s et your brows er to allow
pop- ups for the www.flickr.com domain in
order to us e the "flic kRate this ! "
bookmarklet.

I f you us e the Firefox web brows er and have the G reas emonkey
plug- in (http://greas emonkey.mozdev.org) ins talled, you c an us e
the flic kRate G reas emonkey s c ript, whic h integrates ratings
direc tly into Flic kr. C lic k the G reas emonkey s c ript link from the
flic kRate tools page and c hoos e Tools I ns tall T his U s er
Sc ript... from the Firefox menu. With the s c ript ins talled, brows e
to any Flic kr photo detail page, and you'll s ee the flic kRate form
underneath the photo, as s hown in Figure 3 - 1 9 .

Figure 3-19. flickRate Greasemonkey rating


form
O nc e you've c hos en your rating, c lic k Rate to s end the rating to
flic kRate, all without leaving your main brows ing window.

Browsing Ratings

H alf the fun of us ing flic kRate is s eeing how other us ers have
rated photographs . A s you c an s ee on the flic kRate home page
in Figure 3 - 1 7 , the s ite lis ts the top- rated photos in the three
rating c ategories . You c an als o c lic k the Brows e link at the top of
the home page to s ee photos that have been rated by other
us ers .

Keep in mind that flic kRate is a c ompletely


independent program and is not affiliated
with Flic kr or Yahoo! in any way. I n
addition, flic kRate is a new program that's
s till being tes ted, and there's no guarantee
that it will be here tomorrow. U s e flic kRate
for fun, but don't c ount on your ratings
being around forever.

To s ee jus t the photos you've rated, c hange the value in the


s ec ond drop- down box to "with only my ratings ," and c lic k O K.
You'll s ee jus t the photos you've rated (whic h c an ac t as a
s ec ond "favorites " page to bookmark photos you'd like to view
again).
U nfortunately, at the time of this writing, there's no way to look
up a s pec ific photograph to s ee how it's been rated, but the
applic ation is new and this feature might be added in the future.
A nd you c an always help the author develop his applic ation by
joining in the dis c us s ion at the flic kRate group
(http://www.flic kr.c om/groups /flic krate/).
Hack 19. Travel with Flickr

Flickr Mobile puts Flickr on your cell phone, and once it's in your
hand, you can use Flickr on the go.

You probably know the feeling of arriving home from traveling to


find a pile of unread mail, hundreds of unread email mes s ages ,
and dozens of web s ites to c atc h up with. Without ac c es s to your
home c omputer, you might not be able to keep up, but Flic kr
M obile lets you at leas t drop in on Flic kr onc e in a while to keep
tabs on your friends .

To us e Flic kr M obile, you'll need a c ell phone that c an brows e


the Web and a phone plan that allows data trans fer. M os t c ell
phones made within the pas t few years c an brows e the Web, but
you might need to ac tivate the ability with your c ell provider.

O nc e you've got things working, fire up your mobile web brows er,
point your phone to http://www.flic kr.c om/mob/, and log in. You
s hould s ee the Flic kr M obile home page s hown in Figure 3 - 2 0 .

Figure 3-20. Flickr Mobile home page


O f c ours e, viewing the s tandard Flic kr web s ite on your phone
c ould be a c hore bec aus e of the large image s izes , but Flic kr
M obile s hows you s mall thumbnails only. I t's not an ideal
environment for viewing pic tures , but it's great for keeping up
with photos and c omments when you're on the go. Figure 3 - 2 1
s hows the photo s ize available at Flic kr M obile.

Figure 3-21. Flickr Mobile friends' photos page


O nly a few of the features from the s tandard web s ite are
available on Flic kr M obile. You'll find you and your c ontac ts '
photos and c omments , and you c an brows e photos from
everyone. You c an als o upload photos from your phone [Hack
#6] and add c omments if you're dexterous enough to us e the
keypad.

T he features might be limited at Flic kr M obile, but thanks to the


Flic kr A P I , with s ome s c ripting you c an add your own mobile
features .

Visual Dictionary

I mages trans c end language. A pic ture of a Frenc h tree is s till a


pic ture of a tree, and we all know the word for tree in our own
language. T his is the idea behind the Flic kr V is ual D ic tionary, a
mobile phone applic ation by Flic kr member Steeev
(http://www.flic kr.c om/photos /s teeev/) that lets you s earc h for
photos with s pec ific tags and ac ts as a univers al trans lator.

I magine you find yours elf in Tokyo, no c abs in s ight, and you
need to get ac ros s town. I f you knew J apanes e you c ould eas ily
as k s omeone where you c ould c atc h a c ab, but with the language
barrier, you c ould be s tuc k in tough s pot. O ne option is to bring
up the Flic kr V is ual D ic tionary on your phone by firing up its web
brows er and pointing it to
http://s teeev.f2 o.org/flic kr/s earc h.php? mode=mobile. Type in
the word taxi, and you'll find a number of images on Flic kr tagged
with the word taxi, as s hown in Figure 3 - 2 2 . With a pic ture of a
taxi in your hand, c hanc es are you c an get your mes s age
ac ros s .

Figure 3-22. Flickr Visual Dictionary by Steeev


I f you'd like to build your own Flic kr Trans lator s o that you c an
c us tomize the look and feel, the Flic kr A P I gives you all the
ac c es s you need.

The Code

T he following c ode is a s imple Flic kr Trans lator written with P H P


5 . C opy the following c ode to a file c alled t.php (for s imple
keying on a phone), and be s ure to inc lude your own Flic kr A P I
key:

<?php
// t.php
// A quick mobile search for Flickr that you can use
// as a universal translator while traveling. Search
// for a word you don't know how to say in a foreign
// language on Flickr, and point to a picture of it.
//
// You can get an API key and read the full documentation
// for the Flickr API at http://www.flickr.com/services/api/

// Set your unique Flickr API key


$api_key = "insert your Flickr API key";

// Get the query


if (isset($_GET['q'])) {
$query = $_GET['q'];
$query = urlencode($query);
} else {
$query = "";
}

// Get the page


if (isset($_GET['p'])) {
$page = $_GET['p'];
} else {
$page = 1;
}

print '<?xml version="1.0"?>';


?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "htt
<html>
<head>
<title>Flickr Translator</title>
<meta http-equiv="Content-Type" content="text/html; charset=UT
</head>
<body>
<h1>Flickr Translator</h1>
<?
if ($query == "") {
?>
<form action="t.php" method="get">
<input type="text" name="q"/><br />
<input type="submit" value="Search"/>
</form>
<? } else {
// Construct a Flickr query to grab contacts
$req_url = "http://www.flickr.com/services/rest/";
$req_url .= "?method=flickr.photos.search";
$req_url .= "&api_key=$api_key";
$req_url .= "&tags=$query";
$req_url .= "&tag_mode=all";
$req_url .= "&per_page=5";
$req_url .= "&page=$page";

// Make the request


$response = file_get_contents($req_url);

// Parse the XML


$xml = simplexml_load_string($response);

// Loop through the photos returned, printing them out


foreach ($xml->xpath('//photo') as $photo) {
$id = $photo['id'];
$secret = $photo['secret'];
$server = $photo['server'];
$baseURL = "http://static.flickr.com/";
$thumbURL = "$baseURL$server/$id" . "_$secret" . "_t.jpg";
$mURL = "$baseURL$server/$id" . "_$secret" . "_m.jpg";
print "<a href=\"$mURL\">";
print "<img src=\"$thumbURL\" />";
print "</a><br />";
}

// Add navigation for next page, last page, home


$nextpage = $page + 1;
print "<a href=\"t.php?q=$query&p=$nextpage\">next 5</a>";
if ($page > 1) {
$lastpage = $page -1;
print "<br /><a href=\"t.php?q=$query&p=$lastpage\">last 5</a>
} ?>
<br /><a href="t.php">new search</a>
<? } ?>

</body>
</html>
T his s c ript pres ents a s ingle form field where you c an type a
s ingle tag, or a number of tags s eparated by c ommas . T he s c ript
c ontac ts the Flic kr A P I us ing the flickr.photos.search method
and dis plays the photos in the res pons e five images at a time.
E ac h image is linked to a larger vers ion of the image, s o you c an
zoom in if you find the perfec t pic ture.

Running the Hack

To run the s c ript, upload t.php to a web s erver. O pen your


phone's brows er and type in the U RL , whic h will look s omething
like this :

http://www.example.com/t.php

You s hould s ee a blank form that you c an us e to enter a s earc h


term. C hoos e Searc h, and the s c ript will dis play matc hing
photos , as s hown in Figure 3 - 2 3 .

Figure 3-23. Flickr Translator search for "bus"


Flic kr photos might not be able to form c omplete s entenc es in
another language for you, but you'll at leas t have another tool
you c an us e when traveling.
Hack 20. Build a Custom Flickr Feed

Subscribe to any data available at Flickr by using the Flickr A PI


to build a custom RSS f eed with Flickr photos.

I f you already us e an RSS news reader, you know how c onvenient


it is to have information c ome to you via RSS rather than
s eeking it out. You c an have Flic kr c ontent delivered to you via a
news feed [Hack #17], and you c an als o us e Flic kr RSS feeds to
publis h photos on other web s ites [Hack #1]. T he RSS format is
s o popular that you'll find many exis ting tools that c an c ons ume
the format.

Custom Feeds

Flic kr offers a number of news feeds for mos t of the data you'll
find on the s ite, but you might run into times when you want to
build a c us tom RSS feed that Flic kr does n't provide. H ere's a
quic k look at s ome s ituations where you might want a c us tom
feed:

To view a different image s ize

Flic kr offers s mall thumbnails in its news feeds if you'd


rather s ee large images or the s maller s quare
thumbnails in your news reader, you c an build your own
feed.

To add extended data to a feed

I f you're interes ted in the extended c amera data [Hack


#3] that is s tored with s ome photos , you might want a
feed that inc ludes this data (it's not available in the
default Flic kr feeds ). You c an als o add bits of
information, s uc h as member ic ons , lic ens e information,
and details about the s ets to whic h a photo belongs .

To control the number of items

Flic kr provides the 1 0 mos t rec ent photos in its photo-


related news feeds , but in a c us tom feed you c an inc lude
any number you'd like by s pec ifying a different number of
photos as you make your A P I c all.

To control the look and feel

A c us tom feed gives you c omplete c ontrol over how


titles , des c riptions , and photographers ' names appear in
the feed. I f you want to s how a photo's tags in the feed
des c ription, you c an. I f you'd like to view photos in a
partic ular way in your news reader, you'll need to c reate a
c us tom feed.

To follow nonfeed data

Flic kr does n't provide information about photos marked


as favorites [Hack #25] in an RSS feed. I f you'd like to
s ubs c ribe to s omeone's favorites or follow other types of
data that aren't available in the default news feeds , you
c an build your own.

T his hac k pres ents a very bas ic way to build a c us tom Flic kr
feed with P erl. You c an us e the c ode as a s tarting point for
c reating your own c us tom feeds to trac k your favorite Flic kr
data.

The Code

T he following s c ript c ontac ts the Flic kr A P I with the


flickr.photos.getContactsPublicPhotos method and c reates an
RSS feed with the lis t of photos . T he res ult is s imilar to the feed
as s oc iated with the Your C ontac ts ' page
(http://www.flic kr.c om/photos /friends /), but this c us tom feed
dis plays large images ins tead of the s tandard s mall thumbnails .

You'll need to make s ure you have two nons tandard P erl modules
before you begin: LWP::Simple
(http://s earc h.c pan.org/~gaas /libwww- perl-
5 .8 0 3 /lib/LWP /Simple.pm) c ontac ts the A P I , and XML::Simple
(http://s earc h.c pan.org/~grantm/XM L- Simple-
2 .1 4 /lib/XM L /Simple.pm) pars es the res pons e. You'll als o need
to add your N SI D and Flic kr A P I key, both of whic h you c an find
at the Flic kr A P I s ite (http://www.flic kr.c om/s ervic es /api/).

O nc e the prerequis ites are in plac e, c opy the following c ode to a


file c alled flickr_contact_feed.pl:

#!/usr/bin/perl
# flickr_contact_feed.pl
# Builds a custom RSS feed of contacts' photos for a
# given Flickr user NSID.
#
# You can get an API key, find your NSID, and read the
# full documentation for the Flickr API at:
#
# http://www.flickr.com/services/api/

use strict;
use LWP::Simple;
use XML::Simple;

# Set your NSID and API key


my $nsid = 'insert your NSID';
my $api_key = 'insert your Flickr API key';

# Start the RSS file


print <<"END_HEADER";
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>My Contacts' Photos</title>
<link>http://www.flickr.com/photos/friends/</link>
<description>Photos from my contacts at Flickr</description>
<language>en-us</language>
END_HEADER

# Construct a Flickr Query with only required options


my $language = "en";
my $req_url = "http://www.flickr.com/services/rest/";
$req_url .= "?method=flickr.photos.getContactsPublicPhotos";
$req_url .= "&api_key=$api_key";
$req_url .= "&user_id=$nsid";

# Make the request


my $flickr_response = get($req_url);
# Parse the XML
my $xmlsimple = XML::Simple->new( );
my $flickr_xml = $xmlsimple->XMLin($flickr_response);
my $photolist = $flickr_xml->{photos}->{photo};

# Loop through the items returned, adding as items to feed


foreach my $id (keys %{$photolist}) {
my $secret = $photolist->{$id}->{secret};
my $server = $photolist->{$id}->{server};
my $owner = $photolist->{$id}->{owner};
my $username = $photolist->{$id}->{username};
my $title = $photolist->{$id}->{title};
my $img_src = "http://static.flickr.com/$server/$id\_$secret\_m
my $img_tag = "&lt;img src=\"$img_src\" /&gt;";
my $link = "http://www.flickr.com/photos/$owner/$id/";
print "<item>\n";
print " <title>$title</title>\n";
print " <link>$link</link>\n";
print " <description>$img_tag &lt;br&gt; photo by $username</
print "</item>\n";
}
print "</channel>\n";
print "</rss>";

T he five print c ommands toward the end of the s c ript determine


how RSS items will appear in your news reader. A s you c an s ee,
eac h RSS item inc ludes a title, link, and des c ription. T his s c ript
s ets the photo title as the item title and a link to the photo as
the RSS item link. T he des c ription inc ludes the H T M L nec es s ary
to dis play the photo and a line that indic ates who took the photo.

I t's important to note that the H T M L is es c aped for RSS. T his


bas ic ally means that H T M L brac kets have been turned into their
H T M L entity equivalents : < bec omes &lt; and > bec omes &gt;,
whic h means that, for example, a s tandard <br> tag is
repres ented as &lt;br&gt;. E s c aping H T M L makes for s ome
c onfus ing c ode, but it ens ures that mos t RSS readers will be
able to dis play the H T M L properly.

Running the Hack

You c an run the c ode from a c ommand prompt, piping the res ults
to an XM L file:

flickr_contact_feed.pl > flickr_contact_feed.xml

U pload the output file to a public ly addres s able web s ite and
note the U RL , whic h s hould look like this :

http://www.example.com/flickr_contact_feed.xml

With your U RL in hand, you c an add the new feed to your favorite
news reader. Figure 3 - 2 4 s hows the feed in the Bloglines web-
bas ed news reader.

Figure 3-24. Viewing a custom Flickr feed with


Bloglines
To keep the c us tom feed up to date, you'll want to generate the
file on a regular s c hedule. You c an us e cron on U nix- bas ed
mac hines or the Windows Sc heduler for Windows .

T his hac k s hould give you a s tarting point for building your own
feeds bas ed on data from the Flic kr A P I . With a few minutes of
s c ripting, you c an have muc h more c ontrol over your Flic kr
s ubs c riptions .

See Also

[Hack #17]

[Hack #7]
Hack 21. Set Random Desktop
Backgrounds

Use the Flickr A PI to spin a virtual roulette wheel, and let f ate
choose your desktop background image based on a Flickr tag you
specif y.

P eople love to c hange their des ktop bac kgrounds . I t's one of the
firs t s kills that new c omputer us ers learn, and even old c omputer
pros tend to fiddle with their des ktop bac kground images on a
fairly regular bas is . Brows ing through the ais les of your loc al
c omputer s hop, you'll find C D s full of s c enic imagery that you
c an us e as des ktop bac kground pic tures . But why s hell out
money for c us tom bac kgrounds when you c an us e Flic kr as your
s ourc e for bac kground images ?

A s you're brows ing around Flic kr, you might s pot an image you'd
like to us e as a des ktop bac kground. But if you're like mos t
people, your des ktop is s et at a res olution of 1 0 2 4 x 7 6 8 pixels
or higherquite a bit bigger than the 5 0 0 - pixel- wide images you
s ee at Flic kr. I f you s tretc h the image to fit your des ktop, you
may end up with a blurry, dis torted mes s , rather than the s c enic
vis ta you were hoping for.

L uc kily, many people don't res ize their images [Hack #4] before
they upload them to Flic kr, and you c an often find larger vers ions
of the images you s ee at Flic kr by c lic king the A ll Sizes button
on a photo detail page (Figure 3 - 2 5 ).
Figure 3-25. The All Sizes button on a Flickr
photo page
C lic king the A ll Sizes button takes you to the "A vailable s izes "
page, whic h defaults to s howing you a large vers ion of the image,
as s hown in Figure 3 - 2 6 .

Figure 3-26. The All Sizes page showing a larger


version of a photo
I f you're luc ky, you'll find an image as big as or bigger than your
c urrent des ktop s ize. Right- c lic k anywhere on this larger image
and c hoos e "Set as Wallpaper" in Firefox or "Set as Bac kground"
in I nternet E xplorer. M inimize any open windows , and c hec k out
your new bac kground image.

T his proc es s is eas y to follow anytime you're ready for a new


bac kground, but with a little s c ripting, you c an s peed things up.
T his hac k automatic ally s ets a random des ktop bac kground
image bas ed on a Flic kr tag you provide.

Backgrounds for Windows

T his hac k c ontac ts Flic kr via its web s ervic es A P I , performs an


image s earc h, c hoos es one of the photos at random, downloads
the image, and s ets the photo as your des ktop bac kground.
Bec aus e Windows expec ts des ktop bac kgrounds to be bitmap
(.bmp) images and Flic kr images are J P E G s , the s c ript will als o
have to c onvert the image from a J P E G to a bitmap.

T his c onvers ion proc es s is beyond the s c ope of the Windows


s c ripting environment, and this hac k us es the third- party
s oftware I mageM agic k to c onvert J P E G files to bitmaps . To
ins tall I mageM agic k, brows e to http://www.imagemagic k.org and
c lic k the Binary Releas es link on the left s ide of the page. Sc roll
down to the s ec tion labeled Windows Binary Releas e, and c hoos e
the lates t vers ion. D ownload the file, follow the ins tallation
prompts , and be s ure to c hec k the option to ins tall the
I mageM agic k c ontrol for Windows s c ripting. O nc e you're
finis hed ins talling the program, you'll be s et to run the s c ript.

The code
A dd the following c ode to a file c alled Flickr_Background.vbs :

'-----------------------------------------------------
' Flickr_Background.vbs
'
' Finds a random image via the Flickr API and
' sets it as the desktop background image.
'
' This script depends on Image Magick, which you
' can download here:
'
' http://www.imagemagick.org
'
' Edit the following line to change the "theme" of
' your background. Double-click this file to run it.
'-----------------------------------------------------
strTag = "cityscape"

'-----------------------------------------------------
' Your Flickr API key
'-----------------------------------------------------
Const API_KEY = "insert your Flickr API key"

'-----------------------------------------------------
' Using the query, find a random image via Flickr
'-----------------------------------------------------
'Construct a Flickr search query
strReqURL = "http://www.flickr.com/services/rest/" & _
"?method=flickr.photos.search" & _
"&api_key=" & API_KEY & _
"&tags=" & strTag & _
"&tag_mode=all" & _
"&per_page=200"

'Start the XML Parser


Set MSXML = CreateObject("MSXML.DOMDocument")
'Set the XML Parser options
MSXML.Async = False

'Make the request


strResponse = MSXML.Load(strReqURL)
If MSXML.parseError.errorCode <> 0 Then
WScript.Echo("Error! " + MSXML.parseError.reason)
End If

'Make sure the request loaded


If (strResponse) Then

'Find the total available


Set Photos = MSXML.SelectSingleNode("//photos")
intTotal = Photos.getAttribute("total")
intPerPage = Photos.getAttribute("perpage")
intMax = intPerPage
If CDbl(intTotal) < CDbl(intMax) Then
intMax = intTotal
End If

'Pick a random number


Randomize
RandomNumber = Int(intMax * Rnd + 1)

'Load the results


Set Results = MSXML.SelectNodes("//photo")

'Loop through the results


For x = 0 to Results.length - 1
If x = RandomNumber Then
strImageID = Results(x).getAttribute("id")
strImageSecret = Results(x).getAttribute("secret")
strImageServer = Results(x).getAttribute("server")
strImageTitle = Results(x).getAttribute("title")
strImageURL = "http://static.flickr.com/"
strImageURL = strImageURL & strImageServer & "/"
strImageURL = strImageURL & strImageID & "_"
strImageURL = strImageURL & strImageSecret & "_"
strImageURL = strImageURL & "o.jpg"
End If
Next

'Unload the results


Set Results = Nothing
Set ResultSet = Nothing

End If

If strImageURL = "" Then


WScript.Echo "No image found! Try again."
WScript.Quit
End If

'-----------------------------------------------------
' Save the image locally to the root c:\ folder
'-----------------------------------------------------
' MsgBox("Downloading " & strImageTitle & "...")

strImageFile = Replace(strTag,",","_")

Set fs = CreateObject("Scripting.FileSystemObject")
Set xmlhttp = CreateObject("Msxml2.SERVERXMLHTTP")
xmlhttp.Open "GET", strImageURL, false
xmlhttp.Send(Now)

fs.CreateTextFile "c:/" & strImageFile & ".jpg"

' Create a Stream instance


Dim objStream
Set objStream = CreateObject("ADODB.Stream")

' Open the stream


objStream.Open
objStream.Type = 1 'adTypeBinary
objStream.Write xmlhttp.responseBody
objStream.SaveToFile "c:/" & strImageFile & ".jpg", 2 'adSaveCreat
objStream.Close
Set objStream = Nothing

Set xmlhttp = Nothing


Set fs = Nothing

'-----------------------------------------------------
' Convert the JPEG to a bitmap
'-----------------------------------------------------
Set Converter = CreateObject("ImageMagickObject.MagickImage.1")
Converter.Convert "c:/" & strImageFile & ".jpg", "c:/" & strImageF
Set Converter = Nothing

'-----------------------------------------------------
' Set the newly created bitmap to background
' and refresh
'-----------------------------------------------------
strRegRoot = "HKEY_CURRENT_USER\Software\Microsoft\" & _
"Internet Explorer\Desktop\General\"
strRegRoot2 = "HKEY_CURRENT_USER\Control Panel\Desktop\"

Set Shell = WScript.CreateObject("Wscript.Shell")


Shell.RegWrite strRegRoot & "BackUpWallpaper", "c:\" & strImageFil
Shell.RegWrite strRegRoot & "Wallpaper", "c:\" & strImageFile & ".
Shell.RegWrite strRegRoot2 & "Wallpaper", "c:\" & strImageFile & "
Shell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUser
Set Shell = Nothing
N ote that the firs t line of the s c ript s ets the theme of your
des ktop bac kground. I f you'd like s omething different from
images tagged with citys cape, s imply edit this line to whatever
you'd like to s ee.

Running the hack

Before you run the s c ript, make s ure you unders tand the ris ks .
T his will replac e your c urrent des ktop bac kground with a random
image from Flic kr, s o be s ure you have a bac kup of your c urrent
des ktop bac kground image before you proc eed; otherwis e, you
might los e it forever.

When you're ready to run the s c ript, double- c lic k the s c ript file
or run it from the c ommand line:

Flickr_Background.vbs

You s hould s ee your des ktop bac kground c hange. I f you're not
happy with the image, run the s c ript again. You c an keep running
the s c ript until you s ettle on s omething you likefor example, the
c itys c ape in Figure 3 - 2 7 .

Figure 3-27. A random image tagged with


"cityscape" as a background
I f you want the random fun to c ontinue, you c an plac e this s c ript
in your Startup folder, and you'll find a new bac kground every
time you log into your mac hine. You c an find your Startup folder
at C:\Documents and Settings \[Your Name]\Start Menu\Programs \.
Backgrounds for Macs

Windows us ers aren't the only ones who c an experienc e the fun
that is random des ktop bac kgrounds . I f you jus t us e M ac O S X
to brows e the Web and do a bit of word proc es s ing, you might not
be aware that there's a powerful U nix- bas ed operating s ys tem
under the hood. I n fac t, in addition to the M ac s c ripting
language, A ppleSc ript, M ac O S X s hips with P erl ins talled. T his
hac k takes advantage of both P erl and A ppleSc ript to bring
s ome randomnes s to your des ktop.

The code

P erl is a great language for making H T T P reques ts and working


with the res pons es . But it's not as good as A ppleSc ript at
performing M ac s ys tem tas ks , s uc h as s etting a des ktop image.
L uc kily, a P erl module c alled Mac::AppleScript lets you exec ute
A ppleSc ript c ode from within your P erl s c ripts . To ins tall this
module, you'll need to have the M ac D eveloper Tools
(http://developer.apple.c om/tools /download/) ins talled. O nc e it's
ins talled, open a Terminal window and type the following
c ommand:

sudo cpan Mac::AppleScript

Before you begin, you'll need to ins tall a c ouple more P erl
modules . A s with many other P erl examples in this book, you'll
need LWP::Simple (http://s earc h.c pan.org/~gaas /libwww- perl-
5 .8 0 3 /lib/LWP /Simple.pm) and XML::Simple
(http://s earc h.c pan.org/~grantm/XM L- Simple-
2 .1 4 /lib/XM L /Simple.pm) to make Flic kr A P I reques ts and pars e
the res pons es .

O nc e the prerequis ites are ins talled, add the following c ode to a
file named flickr_background.pl:

#!/usr/bin/perl
# flickr_background.pl
# Accepts a tag and sets a Mac desktop background
# with an image from Flickr that has that tag.
# Usage: flickr_background.pl <tags>

use strict;
use LWP::Simple;
use XML::Simple;
use Mac::AppleScript qw(RunAppleScript);

# Insert your Flickr API key


my $api_key = "insert your Flickr API key";

# Grab the incoming search query


my $tags = join(' ', @ARGV) or die "Usage: flickr_background.pl <q

# Construct a Flickr search query


my $req_url = "http://www.flickr.com/services/rest/";
$req_url .= "?method=flickr.photos.search";
$req_url .= "&api_key=$api_key";
$req_url .= "&tags=$tags";
$req_url .= "&tag_mode=all";
$req_url .= "&per_page=200";

# Make the request


my $response = get($req_url);
# Parse the XML
my $xmlsimple = XML::Simple->new( );
my $xml = $xmlsimple->XMLin($response);

# Grab a random image ID from the results


my @IDs;
my $photolist = $xml->{photos}->{photo};
foreach my $id (keys %{$photolist}) {
push @IDs, $id;
}
my $index = rand @IDs;
my $id = @IDs[$index];

# Use the random ID to build a photo URL


my $server = $photolist->{$id}->{server};
my $secret = $photolist->{$id}->{secret};
my $url = "http://static.flickr.com/";
$url .= "$server/$id" . "_$secret";
$url .= "_o.jpg";

# Save the image locally


my $time = time;
my $image = get($url);
open IMAGE,">$tags-$time.jpg";
print IMAGE $image;
close IMAGE;

# Set the image as the current desktop background


RunAppleScript(qq(
tell application "Finder"
set desktop picture to document file "Aqua Blue.jpg" of folder
end tell));
RunAppleScript(qq(
tell application "Finder"
set desktop picture to document file "$tags-$time.jpg"
end tell));

A s you c an s ee, the las t few lines of the s c ript are A ppleSc ript
ins ide of P erl. T he firs t line of A ppleSc ript s ets a preexis ting
image as the bac kground, and the s ec ond line s ets the newly
c reated file as the bac kground. T his ens ures that the
bac kground will refres h when you run the s c ript.

Running the hack

You c an run the s c ript from the c ommand line, adding a des ktop
theme, like this :

perl flickr_backgound.pl
tags

Running the s c ript with the countrys ide tag, for example, will s et
your bac kground to s omething that looks like Figure 3 - 2 8 .

Figure 3-28. A random image tagged with


"countryside" as a background
While the idea of leaving your des ktop bac kground to c hanc e
might s eem frightening, you might be s urpris ed at the artis tic
and truly bac kground- worthy images people have pos ted to
Flic kr. T his hac k is a great way to s pic e up your des ktop.
Hack 22. Build a Flickr Screensaver

With a bit of Perl and the built-in photo screensavers available


in Mac OS X or Windows XP, you can create your own
screensaver that shows photos f rom Flickr.

A long with des ktop bac kgrounds [Hack #21], s c reens avers have
always been a feature of pers onal c omputers that people feel
c omfortable c hanging, tweaking, fiddling with, and hac king for
fun. A nd with a bit of s c ripting, you c an c reate a photo s lides how
s c reens aver with more meaningful images than flying toas ters .

T his hac k relies on the photo s c reens avers that s hip with
Windows XP and M ac O S X. E ac h s c reens aver lets you s pec ify a
direc tory on your c omputer that c ontains images , and dis plays
thos e images on your s c reen during your idle c omputer
moments . T his hac k us es P erl and the operating s ys tem's
s c heduling features to s ubs c ribe to a Flic kr RSS feed [Hack
#17] with images . A t regular intervals , the s c ript downloads all
of the images from a s pec ific feed into a s pec ial direc tory that
your s c reens aver c an us e.

The Code

T his c ode works on both Windows XP and M ac O S X s ys tems ,


but you'll need a c ouple of c omponents that aren't ins talled by
default: LWP::Simple (http://s earc h.c pan.org/~gaas /libwww- perl-
5 .8 0 3 /lib/LWP /Simple.pm) handles web reques ts , and
XML::Simple (http://s earc h.c pan.org/~grantm/XM L- Simple-
2 .1 4 /lib/XM L /Simple.pm) pars es the Flic kr RSS feed.

C opy the c ode to a file c alled flickr_s creen.pl, and put it in a loc al
folder path where the images will be s tored. O n Windows XP, you
s hould s pec ify a drive and folder, s uc h as C:\FlickrScreen. O n M ac
O S X, you'll want to s pec ify a full path, s uc h as
/Us ers /pb/Photos /FlickrScreen.

You'll als o need to s pec ify one of the many Flic kr RSS feeds
available on the s ite. G roup photo pools work es pec ially wellif
you need a feed to tes t, try the Kite A erial P hotography group
pool feed at
http://www.flic kr.c om/groups /kiteaerialphotography/pool/feed/?
format=rs s _2 0 0 . Remember that the c ode is des igned to read
RSS 2 .0 feeds only, s o be s ure to c hoos e the c orrec t format as
you're s c outing feeds ac ros s Flic kr.

#!/usr/bin/perl
# flickr_screen.pl
# Downloads images in a Flickr RSS feed into a local folder
# you can use for a screensaver.

use strict;
use LWP::Simple;
use XML::Simple;

# Set screensaver directory


my $dir = "insert path to a local folder";

# Set Flickr RSS feed (with photos)


my $rss_feed = "insert Flickr RSS feed URL";

# Make the request


my $response = get($rss_feed);
# Parse the XML
my $xmlsimple = XML::Simple->new( );
my $rss = $xmlsimple->XMLin($response);

# Loop through results


foreach my $item (@{$rss->{channel}->{item}}) {
my $title = $item->{title};
my $photourl = $item->{'media:content'}->{url};
my $link = $item->{link};
my $photog = $item->{'media:credit'}->{content};
my $guid = $item->{guid}->{content};
if ($guid =~ m!photo/(\d{7,10})!) {
$guid = $1;
}
my $file = "$dir/$guid.jpg";
# If the file doesn't already exist, write it
unless (-e $file) {
getstore($photourl,$file);

# And print out the photo info for later reference


print "Saved $title by $photog\n$link\n\n";
}
}

T his c ode reads the feed you s pec ified and downloads the
images s pec ified by eac h U RL in the <media:content> element
within eac h <item> in the feed. T his is the larges t s ize for the
image available at Flic kr. A s it downloads eac h photo, the s c ript
prints the photo title, the photographer name, and a link to the
photo detail page to s tandard output. You c an us e this to log
your downloads and go bac k to find and perhaps c omment on
partic ularly interes ting photos you s ee.
Running the Hack

H ow to run the s c ript is dependent on whic h operating s ys tem


you're us ing.

On Mac OS X

To s et up your s c reens aver on M ac O S X, firs t c reate your Flic kr


s c reens aver photo folder. I t c an be anywhere, but your Pictures
direc tory is a memorable plac e. C all the new folder FlickrScreen,
and be s ure to s et the full path to that folder in flickr_s creen.pl.

To get the ball rolling, open up a Terminal window (A pplic ations


U tilities Terminal), c hange to the direc tory where
flickr_s creen.pl is loc ated (us ing the cd c ommand), and run the
s c ript from the c ommand line, like this :

perl flickr_screen.pl

T his will download and add s everal photos to your FlickrScreen


folder. You c an now s et up your s c reens aver. Selec t Sys tem
P referenc es from the A pple menu, and c hoos e D es ktop & Sc reen
Saver. C lic k the Sc reen Saver button, and then c lic k the C hoos e
Folder... option. Selec t your FlickrScreen folder in your Pictures
direc tory, and you s hould s ee the pic tures you've jus t
downloaded appear in the preview window, as s hown in Figure 3 -
29.
Figure 3-29. Setting a Mac screensaver folder
Your s c reens aver is now s et, and it will dis play the photos you
downloaded. To keep the photos fres h and up to date, though,
you'll want to run flickr_s creen.pl on a regular s c hedule. To s et a
s c hedule, you c an us e the c ommand- line applic ation cron. Keep
your Terminal window open, and type the following c ommand:

crontab -e

T his opens your s c heduled tas ks for editing. To run the s c ript
every day at 8 a.m. and keep a log of the photos the s c ript
downloads , you c ould enter s omething like this :

0 8 * * * perl /Users/pb/Desktop/flickr_screen.pl >> /Users/pb/Des

Keep in mind, though, that the log file will fill up as the s c ript
runs every day. You might want to periodic ally open the log and
delete old entries .

Be s ure to inc lude your own paths for the files . cron is a bit
c ryptic , but it works well for s etting rec urring bac kground tas ks .
N ow that the job is s et, you c an forget about the s c ripting and let
flickr_s creen.pl download photos from Flic kr on a regular bas is .

T he default c ommand- line editor on M ac


O S X is vim, and it c an be an intimidating
interfac e if you're not familiar with it. To
s ave your cron entry, hit the E s c key and
then pres s i to ins ert s ome text. A dd your
cron entry, and when you're done, hit E s c
again. T hen type :wq to s ave (write) the file
and quit.

When the s c ript runs , it will s ave information about the photos it
finds to s creenlog.txt, and you c an us e this information to trac e
an interes ting photo bac k to its detail page at Flic kr.

On Windows XP

T he proc es s for s etting up the s c reens aver on Windows is


almos t identic al to the M ac O S X vers ion. U nlike the M ac ,
however, Windows XP does not c ome with P erl ins talled, s o you
might need to do a bit more work to get s tarted. I f you want to
run P erl on Windows , you c an download the free A c tiveP erl for
Windows by A c tiveState from
http://www.ac tives tate.c om/P roduc ts /A c tiveP erl/.

O nc e P erl is ins talled, c reate your new s c reens aver folder


s omewhere in your files ys tem; C:\FlickrScreen is a good plac e.
Run flickr_s creen.pl from a c ommand line (Start P rograms
A c c es s ories C ommand P rompt) to download s ome
photos :
perl flickr_screen.pl

N ow that s ome photos exis t in the folder, s et your s c reens aver


by right- c lic king any empty s pac e on your des ktop and c lic king
P roperties . C hoos e the Sc reen Saver tab, and s elec t M y P ic ture
Slides how from the lis t of s c reens avers . C lic k the Settings
button, and you s hould s ee the options pic tured in Figure 3 - 3 0 .

Figure 3-30. Windows XP Screen Saver options


U nder the "U s e pic tures in this folder" heading, c lic k Brows e and
c hoos e the Flic ker s c reens aver folder you c reated. C lic k O K,
and your s c reens aver will now s how the photos you jus t
downloaded from Flic kr.

To run the s c ript on a regular s c hedule, you c an us e the Windows


vers ion of cron, c alled s chtas ks . G o bac k to your c ommand
prompt, and type the following c ommand:

schtasks /create /tn "FlickrScreen" /tr "perl c:\flickr_screen.pl

T his c ommand tells Windows to run flickr_s creen.pl every day at


8 a.m. and s ave the output to a file c alled s creenlog.txt.

I t takes a bit of work on either s ys tem to s et up a c us tom Flic kr


s c reens aver, but you'll be rewarded with fres h images on a daily
bas is though, s adly, no flying toas ters . H owever, the Toas ter
G roup pool (http://www.flic kr.c om/groups /toas ter/pool/) on Flic kr
might c ome c los e.
Hack 23. View Flickr Photos on TiVo

Flickr Central f or TiVo's Home Media Engine lets you view Flickr
photos on your television.

M ore and more, we s hare digital vers ions of the pic tures we take.
While it's eas y to pas s around printed photos in any s etting,
s howing digital photos to friends and family c an be tric kier. M os t
c omputers are s et up for one us er at a time, and it's not always
eas y to c rowd a bunc h of people around the monitor.

H owever, our televis ions are almos t always s et up to


ac c ommodate a good number of c omfortable viewers . A nd if
you've already joined the digital televis ion age with T iVo, with a
bit of s etup you c an brows e Flic kr photos on your T V.

What You Need

Flic kr on T V is pos s ible thanks to T iVo's releas e of the H ome


M edia E ngine (H M E ), a way for outs ide developers to c reate
little programs that run on T iVo. D evelopers have c reated
games , weather applic ations , and even RSS readers that you c an
us e through your T V. T he H M E s ys tem us es your home P C to
run the applic ations and a home network to trans fer data, and
the T iVo dis plays the applic ations on your televis ion.

To run H M E , you'll need a T iVo Series 2 that's c onnec ted to your


home network. I f you're us ing the phone line to update your
program data, you'll need to add a network adapter to your T iVo
s etup. You'll find a lis t of c ompatible adapters at
http://c us tomers upport.tivo.c om/knowbas e/root/public /tv2 0 0 6 .htm
Figure 3 - 3 1 s hows a T iVo Series 2 with a L inks ys WU SB1 2
wireles s network adapter.

Figure 3-31. A Series 2 TiVo with a wireless


network adapter
I n addition to running H M E applic ations , a
network adapter will allow you to download
the televis ion s c hedule over your I nternet
c onnec tion ins tead of your phone line.
T hat means no more battles with T iVo over
who gets to us e the phone!

O nc e your T iVo is on your home network, you'll want to be s ure


you c an run H M E applic ations . Brows e to the H M E projec t page
(http://tivohme.s ourc eforge.net), and c lic k the H M E Q uic k Start
link under the For H obbyis ts heading. Take a look at the s ys tem
requirements , download H M E Q uic k Start, and follow the
ins truc tions . I f you run H M E Q uic k Start and s ee a new option
under your T iVo M us ic , P hotos & M ore menu, you'll know you
have everything s et to run Flic kr C entral.

Starting Flickr Central

O nc e you've c onfirmed that your T iVo c an run H M E applic ations ,


download the Flic kr C entral applic ation from
http://home.c omc as t.net/~major_c langer/T iVo/. U nzip the file,
open the new FlickrCentral direc tory, and double- c lic k run.bat. You
s hould s ee the Flic kr C entral launc her s hown in Figure 3 - 3 2 .
Figure 3-32. Flickr Central launcher
To us e all of the features available, c hoos e the A uthentic ate
U s er option and add Flic kr C entral to your lis t of approved
applic ations . To have a few more features , you c an enter your
Flic kr us ername, or, for a bare- bones vers ion, c hoos e the "N o
login" option (but be aware that with this option you'll be able to
view only a c ouple of public photo s ets ).

O nc e Flic kr C entral is running, you s hould s ee "Welc ome to


Flic kr C entral" with a note that the applic ation is running. N ow,
leave your P C , turn on your T V, and hit the T iVo button on your
remote.

Navigating Flickr Central

From the main T iVo menu, c hoos e M us ic , P hotos & M ore. You
s hould s ee the option for Flic kr C entral at the top of the page.
Selec t Flic kr C entral to bring up the initial menu s hown in Figure
3 -3 3 .

Figure 3-33. Flickr Central main menu


You c an ac c es s muc h of what you find on the Flic kr web s ite
through Flic kr C entral, though navigation is muc h different. C lic k
P hotos to s ee the options for viewing photos , as s hown in Figure
3 -3 4 .

Figure 3-34. The Flickr Central Photos menu


T he E veryone's option will s how you the photos found at
http://www.flic kr.c om/photos / (i.e, the mos t rec ent photos from
anyone pos ting to Flic kr). T he C ontac ts ' option will s how you
photos from your c ontac ts , like you'd find at
http://www.flic kr.c om/photos /friends /.

You c an als o view your own photos in order or at random and


brows e photos you've marked as favorites . C hoos ing the Tags
option will take you to a menu where you c an enter any tag you'd
like to s earc h for, as s hown in Figure 3 - 3 5 .

Figure 3-35. Entering a tag at Flickr Central


E ac h photo that you view takes up the entire televis ion s c reen;
there are no thumbnail views of photos in Flic kr C entral. While
you're brows ing a photos tream or s et, you c an c lic k the right or
left arrow on the remote c ontrol to c hange the direc tion of
brows ing. T he up arrow ends your trip through the photos .

I f you c lic k the info button, you'll get a s c reen that inc ludes the
title, the des c ription, and the name of the Flic kr member who
pos ted the photo, as s hown in Figure 3 - 3 6 .

Figure 3-36. Viewing photo details with Flickr


Central
From the main menu, you c an als o view the lates t photos pos ted
to your groups , view your photo s ets , or brows e a lis t of your
c ontac ts , as s hown in Figure 3 - 3 7 .

Figure 3-37. Browsing Flickr contacts at Flickr


Central
You c an us e Flic kr C entral to monitor any new Flic kr ac tivity, but
it does n't work well for partic ipation. For example, you c an't pos t
photos , c omment on others ' photos , or add notes or tags to any
photos .

D es pite thes e limitations , Flic kr C entral is a great way to view


what's happening on Flic kr on T V, and it might be handy for
family gatherings as a new way to s hare your photos .
Chapter 4. Community

H ac ks 2 4 - 2 9

H ac k 2 4 . A dd and Trac k C ontac ts

H ac k 2 5 . Trac k Your Friends ' Favorites

H ac k 2 6 . Find Your Friends ' Favorite Tags

H ac k 2 7 . M ap Your C ontac ts

H ac k 2 8 . Find Flic krites in Your M ac A ddres s Book

H ac k 2 9 . Surf Your C ontac ts


Hacks 24-29
Flic kr is part of a new c ategory of web applic ations c alled s ocial
s oftware. I t's c ons idered s oc ial bec aus e Flic kr lets you c onnec t
with other members in a number of ways . Sharing is built into the
fabric of Flic kr. I ns tead of pos ting your photos to a pers onal,
is olated gallery, you c an s hare them with friends by pas s ing
around your U RL . By inviting people [Hack #24] to partic ipate at
Flic kr, you c an build a c ontac t lis t, and by pos ting c omments and
adding other members to your c ontac t lis t you c an meet other
photographers and have c onvers ations about photos ac ros s
Flic kr.

T his c hapter will s how you how to add c ontac ts at Flic kr and
follow their ac tivity both on and off Flic kr. You'll find out how to
trac k your friends ' favorite photos [Hack #25], vis ualize where
your Flic kr friends are loc ated [Hack #27], and even c ompile a
lis t of your Flic kr c ontac ts ' web s ites [Hack #29] .

By extending the s oc ial features of Flic kr, you'll dis c over s ome
new things about your Flic kr c ontac ts and s ee their photos in a
new light.
Hack 24. Add and Track Contacts

Half the f un of using Flickr is staying in touch with f riends and


f amily by watching their photographs.

Your Flic kr c ontac t lis t repres ents the other Flic kr members that
you want to keep trac k of. I f you add your friends , family, and
other photographers you admire to your lis t, keeping up with
their new photos is a s nap.

Adding Contacts

A s you explore photos on Flic kr, you might s pot a partic ular
photographer whom you'd like to keep up with as s he adds new
photos . To add any Flic kr us er to your c ontac t lis t, you firs t need
to get to that us er's photos tream.

From any photo's detail page, look for a byline in the upper- right
c orner. T he byline will s ay, "U ploaded on [date] by [member]."
C lic king the member's name brings you to her photos tream. A t
the top of the photos tream you'll s ee a link to add that member
as a c ontac t. C lic k the link, mark her as a friend or family
member if you want, and then c lic k O K. T hat member will now be
lis ted among your c ontac ts .
Keep in mind that adding s omeone as a
Flic kr c ontac t is a one- way operation. I f
you add s omeone to your c ontac t lis t, you
won't automatic ally appear on her c ontac t
lis t; s he'll rec eive a notific ation that
you've added her, but s he'll have to
manually add you as a c ontac t if s he wants
to.

I f you want to add s omeone to your c ontac t lis t who is n't yet a
member, you c an s end an email invitation. C lic k I nvite from the
top of any Flic kr page to bring up the I nvitation page s hown in
Figure 4 - 1 .

Figure 4-1. Inviting contacts via email


E nter up to three email addres s es (and their Friend or Family
s tatus , if applic able), c us tomize the mes s age, and c lic k Send.
T he people you lis ted will rec eive emails from Flic kr as king them
to join. O nc e they join, they'll be added to your c ontac t lis t with
the relations hips you s pec ified. Spec ifying people as Friend or
Family means they'll be able to s ee photos that are jus t for them
[Hack #2].

Watching Contacts' Photos

O nc e you have a lis t of c ontac ts , you c an keep up with their


daily pos tings on your c ontac ts page (Figure 4 - 2 ).

Figure 4-2. All of your contacts' recent photos


appear on one page
C lic k Your C ontac ts ' at the top of your Flic kr home page to s ee
rec ent photos . You c an c hoos e to limit the page to c ontac ts
you've des ignated as friends or family members , or to limit the
page to one photo per c ontac t. V iewing your c ontac ts ' rec ent
photos is a great way to s ee what your friends and relations have
been up to lately.

I f you'd rather not have to vis it Flic kr to keep up with your


c ontac ts , you c an us e the RSS and A tom links at the bottom of
the c ontac ts page to keep up with their photos in a news reader
[Hack #17] . Figure 4 - 3 s hows the c ontac ts feed in the Safari
web brows er, whic h doubles as an RSS news reader.

Figure 4-3. Viewing contacts' photos via RSS


C lic king on any of the photos in the feed will take you to that
photo's detail page.

Watching Contacts' Activity

Friends , family, and other Flic kr members c an interac t with your


photos by leaving c omments . C lic k the "Rec ent ac tivity" link
next to the "Your photos " link on your Flic kr home page to s ee
the lates t c omments on your photos . A s with many other s pac es
around Flic kr, you c an als o s ubs c ribe to your rec ent ac tivity via
RSS or A tom [Hack #17], s o you c an keep up with c omments in
your preferred news reader.

Rec ent ac tivity feeds are typic ally us ed to keep tabs on one's
own photos , but you c an us e thos e feeds to s ee rec ent ac tivity
with your c ontac ts ' photos , too. T his will let you know whic h of
your c ontac ts ' photos are getting the mos t c omments , and what
people are s aying about them.

To s tart reading others ' rec ent ac tivity feeds , you need to know
a bit about Flic kr member I D s . I n addition to the member I D you
s ee on a us er's photos tream (e.g., pb), every Flic kr member has
an internal N SI D an alphanumeric s tring that repres ents that
us er behind the s c enes (e.g., 33853652177@N01). O nc e you
have an N SI D in hand, you c an build your own rec ent ac tivity
feed U RL .

A quic k way to find your own N SI D is to brows e to your Flic kr


home page, c hoos e V iew P age Sourc e on your brows er's
menu, and s earc h for the variable global_nsid toward the top of
the page. Whatever this variable is s et to is your Flic kr N SI D .
To find s omeone els e's N SI D , brows e to his photos tream and
c lic k on the P rofile link on the right s ide of the page. From the
P rofile page, you'll find a link that s ays , "Send [member] a
mes s age." Right- c lic k the link, c hoos e C opy L ink L oc ation or
C opy Shortc ut from the menu, and pas te the link into a text
editor s uc h as N otepad. You s hould s ee a U RL like this :

http://www.flickr.com/messages_write.gne?to=33853652177@N01

E verything after the equals s ign is the member's N SI D . J ot down


the member's name and the N SI D , and go to your favorite RSS
news reader. H ere's the format for rec ent ac tivity feed U RL s :

http://www.flickr.com/recent_comments_feed.gne?id=insert NSID&form

I ns ert the N SI D , and add the U RL to your news reader. Repeat


the proc es s for as many of your c ontac ts as you want to watc h.
I f pos s ible, group the feeds together s o you c an brows e them all
at onc e. Figure 4 - 4 s hows a group of c ontac t ac tivity feeds in
the RSS reader Bloglines (http://www.bloglines .c om).

Figure 4-4. Watching contacts' activity at


Bloglines
T he feeds will s till be titled "C omments on your photos ," but
don't let the title fool youyou'll bee s eeing your c ontac ts ' photos
and rec ent c omments people have left about them. I t's a good
way to s ee whic h of your c ontac ts ' photos are generating the
mos t c onvers ation.

See Also

[Hack #17]
Hack 25. Track Your Friends' Favorites

With a weblog tool called Blosxom and some extra Perl, you can
set up a page to show your Flickr contacts' f avorite photos.

Flic kr makes it eas y to s ee new photos pos ted by your


c ontac ts s imply log in and c lic k the Your C ontac ts ' link at the top
of the page (or brows e direc tly to
http://www.flic kr.c om/photos /friends /) to keep up with your
friends ' photos . Flic kr als o makes it eas y to bookmark your
favorite photos by c lic king the "A dd to Favorites " button above
any photo. I t's not eas y to s ee whic h photos your friends and
family have marked as favorites , thoughyou have to view eac h of
your c ontac ts ' favorites lis ts individually by going to eac h one's
photos tream page and c lic king the Favorites link at the top right.

I f you find this a bit c umbers ome, ins tead of viewing all of your
friends ' favorites pages individually and looking for new photos ,
you c an let s ome s c ripting as s emble them for you. You'll need to
do s ome work to put the piec es into plac e, but in the end you'll
have a web page that automatic ally s hows any photos your
c ontac ts mark as favorites . Watc hing your friends ' favorites is a
fun way to s ee photos that are interes ting to your c irc le of
c ontac ts , and you c an us e the page to be s ure you're not
mis s ing great photos .

T his hac k us es the Flic kr A P I to gather a lis t of c ontac ts and


find thos e c ontac ts ' favorite photos . T he weblog s ys tem Blos xom
(http://www.blos xom.c om) then dis plays the lates t photos in
revers e- c hronologic al order, like pos ts on a weblog.
What You Need

T he firs t s tep to implementing this hac k is s etting up Blos xom to


run on your s erver. Blos xom is an extremely lightweight weblog
tool; in fac t, it's only one P erl s c ript (s o, of c ours e, you'll need
web s pac e that c an run P erl C G I s c ripts ).

To s et up Blos xom, grab a c opy of the s c ript blos xom.cgi from


http://www.blos xom.c om and modify the firs t few lines of the
s c ript to matc h your environment. You'll find the s ettings under
the "C onfigurable variables " heading. Be s ure to enter the full
path to the direc tory where the s c ript is ins talled.

You als o might want to reduc e the default number of entries


s hown on the home page from 4 0 to 2 5 ; bec aus e eac h entry will
be a photograph, a lower number will help the page load fas ter.
With thos e s ettings c onfigured, c opy blos xom.cgi to a C G I -
c apable direc tory on your s erver. I f you run into trouble, c lic k the
I ns tall link on the left s ide of the Blos xom home page for
detailed ins tallation ins truc tions for various operating s ys tems .

O ne key to Blos xom's s implic ity is that the s ys tem s tores pos ts
as text files in the files ys tem. T here's no need to have ac c es s to
a databas e or unders tand how to ac c es s a databas e.

To add pos ts to a Blos xom weblog, you s imply c reate a text file
in the proper loc ation. Blos xom rec ognizes the new file and
plac es the text c ontents of the file at the top of the weblog.
T hus , to c reate an automated weblog, you need a s c ript that c an
automatic ally write text files .

The Code
T his P erl s c ript finds all of the c ontac ts for a s pec ific Flic kr us er,
finds thos e c ontac ts ' favorite photos , and writes the H T M L to
dis play the photos as text files .

You'll need a few nons tandard P erl modules before you c an run
the s c ript. T he firs t is Flickr::API
(http://s earc h.c pan.org/~iamc al/Flic kr- A P I /lib/Flic kr/A P I .pm), a
module that makes working with the Flic kr A P I a s nap. T he
s ec ond is XML::Parser::Lite::Tree::XPath
(http://s earc h.c pan.org/~iamc al/XM L- P ars er- L ite-Tree- XP ath-
0 .0 2 /XP ath.pm), a module that helps navigate the Flic kr A P I 's
res pons e XM L .

C reate a text file c alled getFavorites .pl and add the following
c ode. Be s ure to inc lude your own Flic kr N SI D and A P I key
(available at http://www.flic kr.c om/s ervic es /api/) and the
abs olute path to your Blos xom direc tory, inc luding a trailing
s las h.

#!/usr/bin/perl
# getFavorites.pl
#
# Find out which photos your Flickr contacts are
# marking as favorites. This script contacts the
# Flickr API, gets a list of your contacts, and
# finds their favorite photos. You can get a Flickr
# API key and look up your Flickr NSID at:
#
# http://www.flickr.com/services/api/
#
# This script works in conjuction with the weblog
# system Blosxom to display the photos. You can
# download Blosxom and find out how to install it at:
#
# http://www.blosxom.com/
#
# Usage: getFavorites.pl

use strict;
use Flickr::API;
use Flickr::API::Response;
use XML::Parser::Lite::Tree::XPath;

# --- Configurable variables -----


my $nsid = 'insert your Flickr NSID';
my $api_key = 'insert your API key';
my $dir = 'insert path/to/blosxom/directory/';

# --- Script begins -----


# Get list of your contacts
my $api = new Flickr::API({'key' => $api_key});

my $response = $api->execute_method('flickr.contacts.getPublicList
'user_id' => $nsid,
});

# Make sure there's a response


if (!$response->{success}) {
die "Contact list not found! $response->{error_message}";
}

# Parse the response and loop through contacts


my $xpath = new XML::Parser::Lite::Tree::XPath($response->{tree});
my @contacts = $xpath->select_nodes('/contacts/contact');
foreach (@contacts) {
my $username = $_->{attributes}->{username};
my $usernsid = $_->{attributes}->{nsid};
my $userdir = $username;
$userdir =~ s/^\s+//g; # trim leading spaces
$userdir =~ s/\s+$//g; # trim trailing spaces
$userdir =~ s/://g; # transform other spaces
$userdir =~ s/'//g; # transform apostrophes
$userdir =~ s/\///g; # transform slashes
$userdir =~ s/\?//g; # transform question marks
$userdir =~ s/\*//g; # transform asterisks
$userdir =~ s/\.//g; # transform periods
$userdir =~ s/\s/_/g; # underscore spaces, etc.

my $full_dir = $dir . "/" . $userdir;


unless (-d $full_dir) {
mkdir($full_dir);
}

# Find this contact's favorites


my $user_res = $api->execute_method('flickr.favorites.getPubli
'user_id' => $usernsid,
'extras' => 'owner_name',
});

# Make sure there's a response


if (!$user_res->{success}) {
warn "Favorite photos not found! $user_res->{error_message
}

# Parse the response and loop through photos


my $userxpath = new XML::Parser::Lite::Tree::XPath($user_res->
my @photos = $userxpath->select_nodes('/photos/photo');
my $cntPhoto = 0;
foreach (@photos) {
my $id = $_->{attributes}->{id};
my $title = $_->{attributes}->{title};
my $server = $_->{attributes}->{server};
my $secret = $_->{attributes}->{secret};
my $owner = $_->{attributes}->{owner};
my $ownername = $_->{attributes}->{ownername};
my $img_src = "http://static.flickr.com/$server/$id\_$secr
my $href = "http://www.flickr.com/photos/$owner/$id/";
# Make sure there's a title
if (!$title) {
$title = $id;
}

# Write post file with image HTML


my $file = "$full_dir$id.txt";

unless (-e $file) {


open FILE, ">$file" or warn "Can't open $file\n";
print FILE <<"END_POST";
$title

<a href="$href"><img src=\"$img_src\" /></a><br />


<div class="clsByline">photo by <a href="http://www.flickr.com/pho
<div class="clsFavline">favorite of <a href="http://www.flickr.com
END_POST
close FILE;
}
$cntPhoto++;
last if ($cntPhoto == 5);
}
}

T his s c ript c reates a direc tory for every Flic kr member in your
c ontac t lis t. Be aware that if you have 3 0 0 c ontac ts , the s c ript
will c reate 3 0 0 direc tories on your s erver. I n eac h direc tory, the
s c ript will write one text file for every favorite photo from that
c ontac t. T he text file inc ludes the title of the photo and a bit of
H T M L to dis play the photo. E ac h bit of H T M L inc ludes a link to
the original photographer's photos tream, and to the c omplete
lis t of favorites by the pers on who marked the photo as a
favorite. Blos xom handles the work of organizing the mas s of
folders and text files into s omething c oherent.

Running the Hack

To run the s c ript, s imply c all it from a c ommand line like this :

perl getFavorites.pl

T he firs t time you run the s c ript, it will generate text files for
every favorite photo it c an find. Flic kr does n't provide dates for
when a photo was marked a favorite, s o there's no way to
bac kdate photos as marked as favorites on a c ertain date. T his
means that when Blos xom initially dis plays the lis t, it won't be
very meaningful. You'll s imply s ee potentially hundreds of photos
under the s ame date heading. But as you run the s c ript in the
future, any new favorite that's dis played will be noted with the
time it was found as a favorite.

To take advantage of the s c ript, you'll want to run it on a regular


s c heduleevery hour or two. You c an do this with cron on U nix-
bas ed s ys tems , or with the Windows Sc heduler on Windows
s ys tems .

V is it the Blos xom s c ript in a web brows er to s ee the photos .


With the s c ript up and running regularly, you s hould s ee a
frequently updated lis ting of any photos your c ontac ts mark as
favorites , as s hown in Figure 4 - 5 .

Figure 4-5. Friends' favorites weblog


You'll probably need to tweak the default templates in Blos xom
to c hange the look and feel of your friends ' favorites page.
Blos xom has a robus t template s ys tem that lets you c ontrol
every as pec t of the dis play. I n fac t, Blos xom inc ludes a built- in
RSS template, s o you'll find an RSS feed of your friends '
favorites available at:

http://www.example.com/blosxom.cgi?flav=rss

You'll als o find a number of prebuilt templates you c an c hoos e


from at the Blos xom web s ite.

A s you watc h your friend's favorites , you'll s ee a number of


photos that you wouldn't have otherwis e, and they'll have more
meaning than a random s ampling of photos ac ros s Flic kr.

Hacking the Hack

Blos xom is a very hac kable s ys tem, and there are dozens of
plug- ins available that c an add even more features to your
automated weblog. For example, a plug- in c alled categorylis t c an
print a lis t of all the folders under the Blos xom direc tory. With
this hac k, that means you c ould have a lis t of all your c ontac ts
running down the s ide of the page, and c lic king one c ontac t's
name would give you jus t that pers on's favorites on one page, as
s hown in Figure 4 - 6 .
Figure 4-6. Flickr friends' favorites sidebar
V is it the Blos xom plug- in regis try at
http://www.blos xom.c om/plugins / for a look at s ome of the other
available plug- ins .
Hack 26. Find Your Friends' Favorite
Tags

With some Perl and the Flickr A PI, you can see which tags are
most popular among your contacts.

Tagging individual photos [Hack #10] on Flic kr c an help you


organize your own photos . I t als o means Flic kr c an s how
interes ting group patterns , like the Tags page s hown in Figure 4 -
7.

Figure 4-7. Popular tags page


With this page, at a glanc e you c an s ee whic h tags are being
us ed mos t often by all Flic kr members . With a bit of s c ripting,
you c an narrow down this lis t and find out whic h tags are being
us ed mos t by jus t your Flic kr c ontac ts . T his lis t of c ontac ts '
tags is a good way to vis ualize what your friends are interes ted
in, and it's a bit more pers onal than the overall tags page.

The Code

To run this hac k, you'll need a c ouple of nons tandard P erl


modules . M ake s ure you have Flickr::API
(http://s earc h.c pan.org/~iamc al/Flic kr- A P I /lib/Flic kr/A P I .pm)
for working with Flic kr, and XML::Parser::Lite::Tree::Xpath
(http://s earc h.c pan.org/~iamc al/XM L- P ars er- L ite-Tree- XP ath-
0 .0 2 /XP ath.pm) for s orting through the A P I res pons es .

With thos e two modules in plac e, c opy the following c ode to a file
c alled friends _tags _lis t.pl. A dd your N SI D and Flic kr A P I key
(both of whic h you c an find at the Flic kr A P I s ite,
http://www.flic kr.c om/s ervic es /api/) to the c ode.

#!/usr/bin/perl
# friends_tags_list.pl
#
# Find out which tags your Flickr contacts are
# using most often. This script contacts the
# Flickr API, gets a list of your contacts, and
# finds their most popular tags. The script then
# adds up the totals and lists the tags by the
# most popular. You can get a Flickr
# API key and look up your Flickr NSID at:
#
# http://www.flickr.com/services/api/
#
# Usage: perl friends_tags_list.pl

use strict;
use Flickr::API;
use Flickr::API::Response;
use XML::Parser::Lite::Tree::XPath;

# Set your NSID


my $nsid = 'insert your NSID';
my $api_key = 'insert your Flickr API key';
my @tags;
my @sortTags;

# Get your list of contacts


my $api = new Flickr::API({'key' => $api_key});

my $response = $api->execute_method('flickr.contacts.getPublicList
'user_id' => $nsid,
});

# Make sure there's a response


if (!$response->{success}) {
die "Contact list not found! $response->{error_message}";
}

# Parse the response and loop through contacts


my $xpath = new XML::Parser::Lite::Tree::XPath($response->{tree});
my @contacts = $xpath->select_nodes('/contacts/contact');
foreach (@contacts) {
my $usernsid = $_->{attributes}->{nsid};

# Find this contact's tags


my $user_res = $api->execute_method('flickr.tags.getListUserPo
'user_id' => $usernsid,
});
# Make sure there's a response
if (!$user_res->{success}) {
warn "Tags not found! $user_res->{error_message}";
}

# Parse the response and loop through photos


my $userxpath = new XML::Parser::Lite::Tree::XPath($user_res->
my @utags = $userxpath->select_nodes('/who/tags/tag');
foreach (@utags) {
my $match_index = 0;
my $usertagcount = $_->{attributes}->{count};
my $usertag = $_->{children}[0]->{content};

# Make sure there's only one entry for each tag


for my $i ( 0 .. $#tags) {
if ($tags[$i]->{tag} eq $usertag) {
$match_index = $i;
}
}

# If a tag already exists, add to the total


# otherwise, add the new tag to the hash
if ($match_index > 0) {
$tags[$match_index]->{tagcount} = $tags[$match_index]->{tagcount}
} else {
my $thisTag = {
tag => $usertag,
tagcount => $usertagcount,
};
push @tags, $thisTag;
}
}
}
# --- Begin Output -----

# Sort the hashes numerically to put popular tags first


@sortTags = sort { $b->{'tagcount'} <=> $a->{'tagcount'} } @tags;

# Print the tags in a simple text list


foreach (@sortTags) {
my $tagcount = $_->{tagcount};
my $tag = $_->{tag};
print "$tag ($tagcount)\n";
}

T he s c ript fetc hes a lis t of c ontac ts for the given N SI D and us es


the flickr.tags.getListUserPopular A P I method to find the 1 0
mos t popular tags for eac h c ontac t. T he s c ript als o adds the
totals of the tags to s ee whic h tags are the mos t popular ac ros s
all of your c ontac ts .

Running the Hack

To run the s c ript, c all it from a c ommand prompt, piping the


output to a text file, like s o:

perl friends_tags_list.pl > friends_tags.txt

Take a look at friends _tags .txt and you s hould s ee s omething


like the following lis t of tags :
cameraphone (7676)
sanfrancisco (3345)
archive (2999)
7610 (2628)
nyc (1765)
sxsw (1608)
2001 (1512)
sxswi (1259)
travel (1248)
sf (1212)
moblog (1198)
europe (1109)
sxswinteractive (1018)
livemusic (986)
austintx (945)
oregon (733)
sharptm150 (636)
dog (606)
2005 (570)
s700i (559)
lifeblog (523)
nokia6630 (522)
seattle (479)
...

You'll s ee your c ontac ts ' mos t popular tags , along with the
number of times eac h tag has been us ed by your c ontac ts . You
might learn s ome things about your friends that you didn't know
already, and you might find s ome tags that you c an s tart us ing
as well.
Hacking the Hack

I f you want to dis play your c ontac ts ' tags in a tag map with
relative font s izes s imilar to the Tags page at Flic kr, you c an
tweak this s c ript a bit to output H T M L ins tead of text. Replac e
everything after the # --- Begin Output --- c omment with the
following c ode:

# --- Begin Output -----

# Sort the hashes alphabetically


@sortTags = sort { $a->{'tag'} cmp $b->{'tag'} } @tags;

# Print the top of the page


print <<"END_HEADER";
<html>
<head>
<style type="text/css">
body { font-family:arial; width:760px;}
h3 { font: normal 18px Arial, Helvetica, sans-serif; color
</style>
</head>
<body>
<h3>My Contacts' Tags</h3>
END_HEADER

# Print the tags as an HTML Tag Map with relative sizes


foreach (@sortTags) {
my $fontsize;
my $tagcount = $_->{tagcount};
$tagcount /= 10;
my $tag = $_->{tag};
my $minfontsize = 9;
my $fontsize = 9 + $tagcount;
if ($fontsize >= 60) {
$fontsize = 60;
}
$fontsize = sprintf("%.0f", $fontsize);
print "<a href=\"http://www.flickr.com/photos/tags/$tag\"";
print "style=\"font-size:$fontsize";
print "px;font-weight:normal;text-decoration:none;";
print "line-height:110%;\">$tag</a>&nbsp; \n";
}

# Print the bottom of the page


print <<"END_FOOTER";
</body>
</html>
END_FOOTER

T his new c ode s orts the tags alphabetic ally ins tead of by the
number of times eac h tag has been us ed by your c ontac ts . T he
s c ript then generates an H T M L page, giving eac h tag a font s ize
bas ed on the number of times it has been us ed. Run the c ode in
the s ame way, but s end the output to an H T M L file, like this :

perl friends_tag_list.pl > friends_tags.html

O pen friends _tags .html in a brows er, and you'll s ee a lis t of tags
like the one in Figure 4 - 8 .

Figure 4-8. Viewing friends' tags as a tag map


E ac h tag links to the public tag page for that partic ular tag, s o
you c an s ee how Flic kr members ac ros s the s ite have us ed the
tag. With s ome more Flic kr A P I work, you c ould probably find a
way to link to your c ontac ts ' photos for a given tag, but that's
another hac k! I n the meantime, you c an get a quic k glanc e at
your friends ' tagging. A nd onc e you've mas tered your friend's
tags , you might want to try your hand at other ways to make tag
c louds [Hack #14] .
Hack 27. Map Your Contacts

By combining the Flickr A PI and the Google Maps A PI, you can
see how your Flickr contacts are dispersed throughout the
world.

A s you c onnec t with other Flic kr members , you'll notic e that


they c an be anywhere in the world. You might admire a
photographer who lives in a far- off c ountry, and find another
photographer who lives jus t down the s treet. E ven though Flic kr
makes geography irrelevant, it's s till an important part of our
lives . L earning where your Flic kr c ontac ts are bas ed c an tell you
more about them and help you vis ualize jus t how geographic ally
dis pers ed your virtual c ontac ts really are.

A s part of its member profiles , Flic kr allows any member to


inc lude his loc ation. T he loc ation c an range from s omething very
s pec ific , like a c ity and s tate, to s omething general, like a
c ountry. Figure 4 - 9 s hows my own Flic kr profile, with the loc ation
"C orvallis , O R" lis ted direc tly under my web s ite.

Figure 4-9. Flickr profile page with a location set


To find out where a partic ular loc ation is , you c an go to G oogle
M aps (http://maps .google.c om) and type in the full addres s .
Figure 4 - 1 0 s hows a G oogle M ap with a point for the O 'Reilly
headquarters in Sebas topol, C A .

Figure 4-10. An address plotted on a Google Map


C lic king on the point brings up an information window that
inc ludes more G oogle M aps options and the full addres s .

G oogle als o provides a way for developers to c reate their own


maps with their own points and information windows , c alled the
G oogle M aps A P I (http://www.google.c om/apis /maps /). U s ing
this A P I , you c an take a data s ourc e s uc h as your lis t of Flic kr
c ontac ts and build a map bas ed on the loc ation information
they've provided.

Geocoding a Location

T he G oogle M aps A P I needs information about points on a map


in the form of coordinates , or lis tings of latitude and longitude
that repres ent s pec ific geographic points . M os t of us don't know
our c urrent longitude and latitude, and Flic kr does n't expec t us
to. T hat's why the s imple c ity/s tate/c ountry loc ation information
that people enter into Flic kr needs to be geocoded before you c an
build your mapthat is , a lis ting like C orvallis , O R, needs to be
trans lated into its latitude and longitude pair: 4 4 .5 6 4 7 2 2 ,
- 1 2 3 .2 6 0 8 3 3 .

U nfortunately, at the time of this writing, G oogle does n't


explic itly offer a geoc oding s ervic e. H owever, you c an us e
G oogle M aps to get the longitude and latitude of a plac e name by
tweaking a G oogle M aps U RL . A G oogle M aps U RL like the
following will return a bit of J avaSc ript that's intended to be us ed
in s ome G oogle M aps applic ations :

http://maps.google.com/maps?q=insert location &output=js


T he U RL for our example loc ation would be:

http://maps.google.com/maps?q=Corvallis,%20OR&output=js

N ote that the s pac e in the loc ation has been enc oded as %20
bec aus e s pac es aren't allowed in U RL s . I ns ide this page, you'll
find s ome c ode and a bit of s truc tured XM L that looks like this :

...
<locations>
<location infoStyle="/maps?file=li&amp;hl=en" id="A">
<point lat="44.564722" lng="-123.260833"/>
<icon class="noicon"/>
<info>
<address>
<line>Corvallis, OR</line>
</address>
<description></description>
</info>
</location>
</locations>
...

A s you c an s ee, you c an enter a loc ation and get bac k


c oordinates . With s ome s imple s c ripting, you c an automate this
proc es s and geoc ode a large number of plac e names . With this
hurdle out of the way, you c an s imply as s emble your lis t of
plac es and plot them on a map. H owever, you'll need to make
s ure you have what you need before you begin.
What You Need

T he mos t diffic ult part of as s embling this hac k is making s ure


you have the prerequis ites in plac e. You might have to s pend
s ome time gathering the piec es you need, but onc e your
environment is s et, building the map takes only a few minutes .

A s with any of the hac ks in this book that us e the Flic kr A P I ,


you'll need an A P I key. You'll als o need your own Flic kr us er I D
(N SI D ) s o you c an reques t a lis t of your c ontac ts from the Flic kr
A P I . You c an find both of thes e at the Flic kr A P I page
(http://www.flic kr.c om/s ervic es /api/).

To build your own G oogle M ap, you'll need a G oogle M aps A P I


key as s oc iated with a public domain. For example, if you're going
to view your map at a s pec ific web addres s s uc h as
http://www.example.com, you'll need to regis ter that domain with
G oogle when you reques t your key. A nd if you're going to view
your map at a s ubdirec tory s uc h as
http://www.example.com/path/to/map/, you'll need to s pec ify the
path as well when you regis ter for a key. T he requirement for a
s pec ific domain is a limitation of G oogle M aps , but it's a free
s ervic e and you'll need to play by their rules . You c an regis ter
your domain and get an as s oc iated key at
http://www.google.c om/apis /maps /.

I f you're not planning to make your Flic kr


c ontac ts map public , you c an as s oc iate
your G oogle M aps A P I key with the U RL
http://localhos t/. T hat way, you c an ac c es s
the map on a web s erver running on your
loc al mac hine.
T he P erl s c ript for this hac k that writes the J avaSc ript requires
s everal P erl modules that aren't us ually preins talled on mos t
s ys tems . Flickr::API (http://s earc h.c pan.org/~iamc al/Flic kr-
A P I - 0 .0 7 /lib/Flic kr/A P I .pm) handles working with the Flic kr
A P I , and XML::Parser::Lite::Tree::XPath
(http://s earc h.c pan.org/~iamc al/XM L- P ars er- L ite-Tree- XP ath-
0 .0 2 /XP ath.pm) helps pars e the Flic kr res pons es . You'll als o
need URI::Escape (http://s earc h.c pan.org/~gaas /U RI -
1 .3 5 /U RI /E s c ape.pm) for enc oding loc ations for us e in a U RL
and LWP::Simple (http://s earc h.c pan.org/~gaas /libwww- perl-
5 .8 0 3 /lib/LWP /Simple.pm) for pas s ing thos e loc ations to G oogle
M aps for geoc oding.

The Code

T he following P erl s c ript does the heavy lifting for the hac k by
finding the loc ations as s oc iated with your Flic kr c ontac ts ,
looking up the c oordinates for thos e loc ations at G oogle, and
writing the nec es s ary J avaSc ript to dis play the points on a map.
T he s c ript als o as s embles the H T M L nec es s ary to dis play your
c ontac ts ' buddy ic ons in the map its elf.

C opy the following c ode to a file c alled gmap-contacts .pl, and be


s ure to inc lude your own Flic kr N SI D and A P I key in the c ode:

#!/usr/bin/perl
# gmap-contacts.pl
# This script creates a JavaScript file that plots points
# on a Google Map for a given Flickr member's contacts.
#
# You can get a Flickr API key, find your NSID, and read the
# full documentation for the Flickr API at:
#
# http://www.flickr.com/services/api/
#
# You can get a Google Maps API key and read the full
# documentation for the Google Maps API at:
#
# http://www.google.com/apis/maps/

use strict;
use Flickr::API;
use Flickr::API::Response;
use LWP::Simple;
use XML::Parser::Lite::Tree::XPath;
use URI::Escape;

# Set your NSID


my $nsid = 'insert your Flickr NSID ';
my $api_key = 'insert your Flickr API key ';

# Start the API


my $api = new Flickr::API({'key' => $api_key});

my @users;
my @locations;

# Start the JavaScript file, and set the initial center point
# for the Google Map
print <<JSHEADER;
function addMapPoints( ) {
map.addControl(new GSmallMapControl( ));
map.centerAndZoom(new GPoint(-96.66, 40.817 ), 13);
JSHEADER
# Get a list of contacts
my $response = $api->execute_method('flickr.contacts.getPublicList
'user_id' => $nsid,
});

# Make sure there's a response


if (!$response->{success}) {
die "Contact list not found! $response->{error_message}";
}

# Parse the response and loop through contacts


my $xpath = new XML::Parser::Lite::Tree::XPath($response->{tree});
my @contacts = $xpath->select_nodes('/contacts/contact');
foreach (@contacts) {
my ($location,$lat,$lon,$lonlat,$near);
my $usernsid = $_->{attributes}->{nsid};

# Find this contact's location


my $user_res = $api->execute_method('flickr.people.getInfo', {
'user_id' => $usernsid,
});

# Make sure there's a response


if (!$user_res->{success}) {
warn "\nLocation for user $usernsid not found! $user_res->
}

# Grab location w/ regex


if ($user_res->{_content} =~ m!<location>(.*?)</location>!gis)
$location = $1;
} else {
warn "\nNo location found for user $usernsid";
}
# Find Lat/Lon for location at Google
if ($location ne "") {
my $esc_location = uri_escape($location);
my $url = "http://maps.google.com/maps?q=$esc_location&out
my $response = get($url);
# Note if the location has a related longitude/latitude
if ($response =~ m!<point lat="(.*?)" lng="(.*?)"/>!gis) {
$lat = $1;
$lon = $2;
$lonlat = "$lon,$lat";
# Otherwise, warn the user that the coordinates can't be f
} else {
warn "\nNo coordinates found for location $location";
}
# Normalize the name, if possible
while ($response =~ m!<line>(.*?)</line>!gis) {
$near = $1;
$near =~ s! \d{5}!!gs; #Remove Zips
}
}

# Save location to the locations array


my $exists = grep $locations[$_]{lonlat} eq $lonlat, 0 .. $#lo
if (($exists eq 0) && ($lonlat ne "")) {
my $thisLoc = {
lonlat => $lonlat,
lon => $lon,
lat => $lat,
near => $near,
};
push(@locations, $thisLoc);
}

# Save user to the user array


my ($iconserver,$username,$realname,$photosurl);
if ($user_res->{_content} =~ m!iconserver="(\d{1,2})"!s) {
$iconserver = $1;
}
if ($user_res->{_content} =~ m!<username>(.*?)</username>!s) {
$username = $1;
}
if ($user_res->{_content} =~ m!<realname>(.*?)</realname>!s) {
$realname = $1;
}
if ($user_res->{_content} =~ m!<photosurl>(.*?)</photosurl>!s)
$photosurl = $1;
}
my $thisUser = {
nsid => $usernsid,
iconserver => $iconserver,
username => $username,
realname => $realname,
photosurl => $photosurl,
lonlat => $lonlat,
};
push(@users, $thisUser);
}

# Loop through the locations, adding users for that location


# to info window HTML
for my $i ( 0 .. $#locations) {
my $lonlat = $locations[$i]{lonlat};
my $near = $locations[$i]{near};

# Start HTML for info window


my $html = "<b>$near</b><div style=\"width:200px;\">";

# Find users for this location


for my $j ( 0 .. $#users) {
my $user_lonlat = $users[$j]{lonlat};
if ($lonlat eq $user_lonlat) {
my $nsid = $users[$j]{nsid};
my $username = $users[$j]{username};
my $realname = $users[$j]{realname};
$realname = s!'!\\'!g; #Escape apostrophes for JavaScr
my $photosurl = $users[$j]{photosurl};
my $iconserver = $users[$j]{iconserver};
my $iconsrc;
# If no buddy icon is found, use the standard default
if ($iconserver eq 0) {
$iconsrc = "http://www.flickr.com/images/buddyicon
} else {
$iconsrc = "http://photos$iconserver";
$iconsrc .= ".flickr.com/buddyicons/$nsid";
$iconsrc .= ".jpg";
}
$html .= "<div style=\"float:left;padding:3px;\">";
$html .= "<a href=\"$photosurl\" title=\"$realname\">"
$html .= "<img src=\"$iconsrc\" width=\"48\" height=\"
$html .= " border=\"0\" />";
$html .= "</a>";
$html .= "</div>";
}
}
$html .= "</div>";

# Print out the line of JavaScript for this point


if ($lonlat ne "") {
print "\tcreateMarker(new GPoint($lonlat),'$html');\n";
}
}

# Print the last character to close the JavaScript function


print "}\n";
A s you c an s ee, the c ode is fairly c omplex, but it as s embles
everything you need for your map quic kly. Bec aus e many Flic kr
us ers c an be from the s ame loc ation, the s c ript s tores both
loc ations and Flic kr member information in the arrays @locations
and @users. A t the end of the s c ript, the las t loop runs through
the loc ations , building the H T M L nec es s ary to dis play buddy
ic ons from members in eac h loc ation.

Running the Hack

O nc e the s c ript is ready to go, run it from the c ommand line and
s pec ify a des c riptive name for the J avaSc ript file, s uc h as
addMapPoints .j s , like this :

gmap-contacts.pl > addMapPoints.js

T he s c ript will build the J avaSc ript file and note any loc ations it
c ouldn't trans late into c oordinates . N ext, you'll need to put
together the s tandard H T M L file that will hold the map. C reate a
text file c alled contacts -map.html and add the following H T M L ,
making s ure to inc lude your G oogle M aps A P I key and the
J avaSc ript file you jus t c reated in the header:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ut
<title>Flickr Contacts, Mapped</title>
<script src="addMapPoints.js " type="text/javascript"></script
<script src="http://maps.google.com/maps?file=api&v=1&key=inse
type="text/javascript"></script>
<style type="text/css">
body {
font-family:arial,helvetica,sans-serif;
}
</style>
</head>

<body onload="addMapPoints( ); ">


<h1>Flickr Contacts, Mapped</h1>
<div id="map" style="width:800px;height:600px;border:solid #C3CEAE
<script type="text/javascript">
//<![CDATA[
// Create a "tiny" green marker icon
var icon = new GIcon( );
icon.image = "http://labs.google.com/ridefinder/images/mm_20_g
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

var map = new GMap(document.getElementById("map"));

// Creates a tiny green marker at the given point


function createMarker(point,html) {
var marker = new GMarker(point, icon);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function( ) {
marker.openInfoWindowHtml(html);
});
}
//]]>
</script>
</body>
</html>

N ote in the <body> tag that the page will run the addMapPoints()
func tion onc e the page has loaded. T his func tiongenerated by
gmaps -contacts .pl and s tored in addMapPoints .j s initializes the
G oogle M ap and adds all of the points and c ontac t information.

A ls o note that, in this example, the initial c enter of the map is


s et to - 9 6 .6 6 , 4 0 .8 1 7 roughly the middle of the U nited States . I f
mos t of your Flic kr c ontac ts are in the U K, you might want to
c hange this value s o that you don't have to drag the G oogle M ap
to a new loc ation to s ee your c ontac ts ' loc ations . You c an
c hange this value by editing the third line of addMapPoints .j s or
by c hanging the c oordinates in the gmaps -contacts .pl s c ript that
writes that file.

O nc e both files are in plac e on your s erver, bring up contacts -


map.html in a web brows er, and you s hould s ee a map like the
one s hown in Figure 4 - 1 1 .

Figure 4-11. Flickr contacts on a Google Map


C lic k any of the green points on the map, and you'll s ee an info
window c ontaining the Flic kr buddy ic ons that repres ent your
c ontac ts from that loc ation. You c an hover over a buddy ic on to
s ee the member's real name, or c lic k the ic on to view that
member's photos tream at Flic kr.

A nd, of c ours e, you c an zoom or c lic k and drag the map, jus t as
you c an with any G oogle M ap. You c an even drag the map to
other c ountries and s ee if you have c ontac ts there. M os t
importantly, you'll s ee how your Flic kr c ontac ts are dis pers ed,
whic h might help you realize that Flic kr really is a way to s hare
photos with people throughout the world.
Hack 28. Find Flickrites in Your Mac
Address Book

Find anyone in your A ddress Book that has a Flickr photostream.

I f you us e the M ac A ddres s Book to organize your c ontac ts , you


probably have dozens of entries for friends , family members ,
c oworkers , and ac quaintanc es . With a large lis t, the odds are
good that at leas t a few of them have Flic kr members hips . You
might be c onnec ted to your c los es t c ontac ts on Flic kr already,
but finding out who els e in your lis t of pers onal c ontac ts is on
Flic kr c an give you more people to c onnec t with.

You c ould c opy and pas te eac h of your c ontac ts ' email
addres s es into the P eople Searc h page at Flic kr
(http://www.flic kr.c om/find.gne), but s ome quic k s c ripting c an
s ave you time. M ac O S X is a highly s c riptable environment, and
this hac k s hows how you c an us e A ppleSc ript and the underlying
U nix tool c alled curl to find people in your A ddres s Book that
als o have Flic kr photos treams .

The Code

O pen the A ppleSc ript Sc ript E ditor in /Applications /AppleScript


and enter the following c ode. Be s ure to enter your own Flic kr
A P I key, and s ave the s c ript with a memorable name, s uc h as
Find Flickerites .
(*
Find Flickr Members in Address Book

The script loops through people in your Address Book, checking Fli
to see if they're members. If a photostream is found, you
have the option to view it in your default browser. You can get a
Flickr API key at http://www.flickr.com/services/api/.

by Paul Bausch
*)

-- set your Flickr API key

set apiKey to "insert your API key"

-- set some variables for the curl command

set userAgent to "Mozilla/5.0 (Macintosh; U; PPC Mac OSX; en-us)"


set curlCommand to "curl -i -b -A -L \"" & userAgent & "\" "

-- open Address Book and loop through people

tell application "Address Book"


repeat with thisPerson in the people
set thisName to name of thisPerson
repeat with thisAddress in email of thisPerson
set thisEmail to value of thisAddress

-- build the URL that will search for the Wish List

set baseURL to "http://www.flickr.com/services/rest/?me


set thisURL to baseURL & "flickr.people.findByEmail\\&a
set thisURL to thisURL & "\\&find_email=" & thisEmail
-- use curl to fetch the search page
set thisResponse to do shell script curlCommand & thisU

-- if the Wish List URL is found in headers, prompt us


if thisResponse contains "nsid=" then
set theAction to display dialog thisName & " has a
if button returned of theAction is "View" then

-- build Flickr URL based on returned NSID, and bri

set beginID to (offset of "nsid=" in thisResponse)


set thisNSID to get text beginID thru (beginID + 15

set beginID to 1
set endID to (offset of "\"" in thisNSID) - 1
set thisNSID to get text beginID thru endID of this

tell application "Safari"


activate
open location "http://www.flickr.com/photos/" &
end tell
end if
end if
end repeat
end repeat
end tell

T he top of the s c ript s ets s ome variables for curl that will be
us ed later.

I f you'd like to learn more about curl and


what the s ettings in the s c ript mean, open
a Terminal window (found in
Applications /Utilities /) and type man curl.
You'll get the c omplete doc umentation that
explains what all of the c ommand s witc hes
do, and a lis t of all of the options available.

With the variables s et, the s c ript loops through all of the entries
in the A ddres s Book, looking for email addres s es . E ac h
individual email addres s found is us ed to build a Flic kr A P I
reques t U RL with the flickr.people.findByEmail method. O nc e
the U RL is s et, the do shell script c ommand us es curl to fetc h
the res pons e, and the contains c ommand looks for a Flic kr N SI D
as s oc iated with the email addres s .

I f a Flic kr N SI D is found, the s c ript us es display dialog to bring


up a window with V iew and I gnore options . I f you c lic k V iew, the
s c ript will open the Safari brows er, whic h will take you to that
Flic kr member's photos tream. From there, you c an view that
pers on's photos , take a look at her profile details , or add her as
a c ontac t.

Running the Hack

You c an run the s c ript by c lic king the Run button in the Sc ript
E ditor. A s you find people in your A ddres s Book who are als o on
Flic kr, you'll have the option to view their photos treams , as
s hown in Figure 4 - 1 2 .
Figure 4-12. AppleScript prompt to view a
contact's photostream

To keep this s c ript one c lic k away from your A ddres s Book,
move the s c ript to the /Library/Scripts /Addres s Book Scripts
folder. T his way, you c an ac c es s the s c ript from your A ddres s
Book's Sc ripts menu. Run the s c ript at any time by s elec ting
Sc ript M enu Find Flic kerites from the A ddres s Book
applic ation's menu bar.

Finding fellow Flic kr us ers via your A ddres s Book may help you
learn more about s ome people you know c as ually and build your
own lis t of c ontac ts at Flic kr.
Hack 29. Surf Your Contacts

Find out what your contacts are up to outside of Flickr.

M os t of your Flic kr c ontac ts really do have lives outs ide of


Flic kr, and you c an often find a link to a friend's other life on his
Flic kr profile page. When you c reate a Flic kr profile, you have the
option to enter your web s ite U RL and web s ite name, whic h will
s how up in your profile jus t above your loc ation. M os t Flic kr
members us e this s pac e to point to their home pages or
weblogs .

I f you don't already regularly vis it your Flic kr c ontac ts ' external
s ites , you might learn s omething more about your ac quaintanc es
and the photographers you admire by taking a look. I f you have
jus t a handful of c ontac ts , you c ould vis it eac h of your c ontac ts '
profile pages one by one and make a lis t of U RL s you'd like to
vis it; but if you have more than a dozen c ontac ts , a bit of P H P
s c ripting c an help you put together a mas ter s urfing lis t in a few
minutes .

T his hac k c ompiles a lis t of your c ontac ts , as s embles their


profile page U RL s , and vis its eac h one, looking for a web s ite.
You'll need a free Flic kr A P I key and your Flic kr N SI D , both of
whic h c an be found at the Flic kr A P I doc umentation page
(http://www.flic kr.c om/s ervic es /api/). T his hac k als o relies on
the s imple XM L tools built into P H P 5 , whic h make working with
Flic kr A P I res pons es a s nap.
The Code

C opy the following c ode to a file c alled flickr_s urf.php, and be


s ure to put in your own Flic kr A P I key and Flic kr N SI D :

<?php
// flickr_surf.php
// Finds web sites of Flickr contacts for given
// Flickr NSIDs. Use it to gather your Flickr
// contacts' web sites onto one page for easy
// surfing.
//
// You can get an API key and read the full documentation
// for the Flickr API at http://www.flickr.com/services/api/

// Set your Flickr API key and your user NSID


$api_key = "insert your Flickr API key";
$my_nsid = "insert your Flickr NSID";

// This is a greedy script requiring lots of time


set_time_limit(0);

// Construct a Flickr query to grab your contacts


$req_url = "http://www.flickr.com/services/rest/";
$req_url .= "?method=flickr.contacts.getPublicList";
$req_url .= "&api_key=$api_key";
$req_url .= "&user_id=$my_nsid";

// Make the request


$flickr_contacts = file_get_contents($req_url);

// Parse the XML


$fc_xml = simplexml_load_string($flickr_contacts);
?>
<html>
<head>
<style type="text/css">
BODY {
font-family:verdana,arial;
font-size:10pt;
line-height:130%;
}
</style>
</head>
<body>
<h2>Surf Flickr Friends</h2>
<ul>
<?php
// Loop through the contacts
foreach ($fc_xml->xpath('//contact') as $contact) {
$nsid = $contact['nsid'];
$username = $contact['username'];

// Construct a Flickr query to grab contact info


$req_url = "http://www.flickr.com/services/rest/";
$req_url .= "?method=flickr.people.getInfo";
$req_url .= "&api_key=$api_key";
$req_url .= "&user_id=$nsid";

// Make the request


$contact_info = file_get_contents($req_url);

// Parse the XML


$ci_xml = simplexml_load_string($contact_info);

// Get contact info


$iconserver = $ci_xml->person[0]['iconserver'];
$realname = $ci_xml->person[0]->realname;
$profile_url = $ci_xml->person[0]->profileurl;
// See if a web site exists on the member's profile page
// with screen-scraping
$profile_html = file_get_contents($profile_url);
$regex = '!<p style="font-size: 14px;">.*?<a ';
$regex .= 'href="(.*?)"><strong>(.*?)</strong></a>!is';
if (preg_match($regex,$profile_html, $matches)) {
$contact_siteurl = $matches[1];
$contact_sitename = $matches[2];

// If a web site is found, print out the web site URL


// and contact info
print "<li style=\"margin-bottom:10px;\"><a href=\"$contac
print "$contact_sitename</a><br />";
print "<span style=\"font-size:8pt;color:#666;\">";
print "by <a href=\"$profile_url\">$username</a> /";
print " $realname</span></li>\n";
}
$matches = "";

// Sleep for 3 seconds to give the Flickr


// servers a break
sleep(3);
}
?>
</ul>
</body>
</html>

You'll notic e that the s c ript c ontac ts the Flic kr A P I to find your
lis t of c ontac ts , and then c ontac ts the A P I again for eac h
c ontac t to find the us er's real name and profile U RL . Flic kr
does n't make s ite information available via the A P I , s o the
s c ript relies on s creen-s craping the profile pages to find that
data. Sc reen- s c raping involves downloading the H T M L of the
page and pic king through it with regular expres s ions to c herry-
pic k the required information. I t's a notorious ly brittle proc es s ,
and if Flic kr c hanges the H T M L of the profile page, the s c ript
won't be able to find the information you want. Be aware that you
may need to tweak the regular expres s ion s et as $regex to find
the web s ite name and U RL .

N ote als o that the s c ript is fairly reques t- intens ive. For every
pers on in your c ontac t lis t, this s c ript will make two reques ts of
the Flic kr s ervers . To give the Flic kr s ervers a bit of a break, the
s c ript then res ts for three s ec onds by c alling sleep(3). T his will
give the Flic kr s ervers a s mall res t between eac h c ontac t, but it
als o means you'll need to be patient while the s c ript is c ompiling
your lis t.

Running the Hack

To run the c ode, upload the s c ript to your web s erver and brows e
to the page. T he U RL s hould look s omething like this :

http://www.example.com/flickr_surf.php

Bec aus e of the numerous H T T P reques ts and the built- in delay,


expec t your s c ript to take s everal minutes to exec ute. A nd, of
c ours e, the more c ontac ts you have, the more time the s c ript
will need to c ompile the lis t. When it's finis hed, you s hould s ee a
lis t of web s ites from your Flic kr c ontac ts like the one in Figure
4 -1 3 .
Figure 4-13. A list of the author's Flickr
contacts' web sites
I f you want to vis it the page over and over again, you'll want to
s ave the H T M L the s c ript generated rather than rebuilding the
lis t eac h time you vis it the page. To s ave the H T M L , c hoos e File
Save A s ... (or File Save P age A s ...) from your
brows er's menu. Your c ontac ts ' web s ites s houldn't c hange too
often, and when you add or remove c ontac ts you c an vis it
flickr_s urf.php again to rec ompile the lis t and bring it up to date.
Chapter 5. Maintenance

H ac ks 3 0 - 3 6

H ac k 3 0 . Bac k U p Your P hotos

H ac k 3 1 . Bac k U p P hoto C omments

H ac k 3 2 . M ake a C ontac t Sheet

H ac k 3 3 . D ownload a L is t of P hotos

H ac k 3 4 . C ac he P hotos L oc ally

H ac k 3 5 . E dit P hotos as a Batc h

H ac k 3 6 . C lean the (G roup) P ool


Hacks 30-36
O nc e you're a Flic kr power us er, you'll find that if you want to
keep your photo c ollec tion in top s hape, it helps to go beyond
the exis ting tools on Flic kr. While maintenanc e c an be a c hore,
there are s ome ways to s peed things up s o you c an get bac k to
the more fun features of Flic kr.

T his c hapter will s how you s ome tips and tric ks for managing a
large c ollec tion of photos on Flic kr, inc luding editing s everal
photos at onc e [Hack #35] and downloading a c omplete lis t of
your photos [Hack #33] . I f you have a large c ollec tion of photos
on Flic kr, you'll find out how to bac k up your photos [Hack #30]
and c omments [Hack #31] to your loc al c omputer for
s afekeeping. A nd if you've s tarted a Flic kr group, you'll find out
how to extend the management features by c reating a
maintenanc e bot [Hack #36] to help you keep the group running
s moothly.
Hack 30. Back Up Your Photos

A Java application called FlickrBackup can snag copies of all of


your Flickr photos so you have local backups.

I f you us e your c omputer to upload photos to Flic kr, c hanc es are


you already have loc al c opies of all of your original images
(es pec ially if you follow the ins truc tions in [Hack #4] before
s ending them). But if you us e Flic kr to s tore photos taken with
your mobile phone [Hack #6], the photos at Flic kr might be your
only c opies . I n this c as e, you'll definitely want to bac k up your
photos onc e in a while by s aving c opies of your Flic kr photos
loc ally.

You c ould write your own Flic kr A P I s c ript to grab all of your
photos , but luc kily, A ndrew Serff has s aved you the trouble by
writing a free J ava program c alled Flic krBac kup
(http://www.s unkenc ity.org/flic krbac kup/). T he program runs on
both M ac s and P C s , and it provides a vis ual interfac e for
bac king up your Flic kr photos . You c an download a c opy of
Flic krBac kup from its Sourc eForge projec t page at
http://www.s ourc eforge.net/projec ts /flic krbac kup.

O nc e you've downloaded the file, unzip the c ontents . To s tart the


program on M ac O S X, open the folder and double- c lic k
FlickrBackup.j ar. O n Windows , open a c ommand prompt (Start
P rograms A c c es s ories C ommand P rompt),
c hange direc tory (cd) to the FlickrBackup folder, and type the
following c ommand:
$ java -jar FlickrBackup.jar

T his c ommand will s tart the program, and you'll be greeted with
the authentic ation reques t s hown in Figure 5 - 1 .

Figure 5-1. FlickrBackup authentication request

O nc e you've authentic ated at Flic kr in your brows er, return to


the reques t window and c lic k O K. T he program will s ave your
authentic ation information, s o you'll have to authorize it only
onc e.

Flic krBac kup will download thumbnails of all of your photos , and
you'll s ee a grid of your photos like the one s hown in Figure 5 - 2 .
Figure 5-2. Flickr Backup photo selection
window
From here, you c an s elec t whic h photos to bac k up. A t the time
of this writing there's no way to s elec t all photos at onc e, s o
you'll need to c lic k eac h photo individually. A lternately, you c an
c hoos e to bac k up c omplete photo s ets at Flic kr by c lic king the
Sets tab.

O nc e you've made your s elec tion, c lic k Bac kup Selec ted, and
you'll s ee the Flic kr Bac kup Wizard window. C lic k the Brows e
button and c hoos e a loc al folder to s tore images in, and Start
Bac kup will begin the proc es s . A s tatus bar will let you know how
the program is doing.

Flic krBac kup does n't s tore titles ,


des c riptions , tags , notes , or c omments jus t
photos . I t's a quic k way to c opy your
Flic kr photos , but keep in mind that it
won't give you bac kups of the as s oc iated
data s tored at Flic kr. I f you'd like to s ave
bac kups of c omments about your photos ,
c hec k out the next hac k.

P hotos will be s tored with their Flic kr I D s , and when the


operation is c omplete you s hould find a s eries of J P E G s in your
bac kup folder with names like 4574244_ff80b1164f_o.j pg. You
c an leave the bac kups on your hard drive, or c opy your photos to
a C D or D V D for long- term s torage. Flic krBac kup is a quic k way
to c opy a large number of photos without writing a line of c ode.
Hack 31. Back Up Photo Comments

Flickr photo comments are usually light chit-chat, but you might
want to save them f or posterity.

O ne of the key features of Flic kr is that it enables its us ers to


have c onvers ations about photos on the s ite. When you pos t
photos on Flic kr, you're pos ting them not into an empty s pac e,
but into a s pac e with lots of other members . Bec aus e Flic kr is an
interac tive environment, your c ontac ts and other viewers c an
not only view your photos , but als o pos t c omments about them,
perhaps as king ques tions , offering prais e, obs ervations , or
providing us eful c ritiques . Figure 5 - 3 s hows three c omments
under a photo.

Figure 5-3. Photo comments


E ven though Flic kr will be around for the fores eeable future, you
might want to have your own pers onal bac kups of the c omments
that have been generated around your photos . T he
c onvers ations about a photo are often nothing more than idle
c hit- c hat, but as with any c onvers ations , there may be times
when you'll wis h you had a c opy to refer bac k to or s earc h
through, or jus t to have a rec ord of what was s aid.

With a bit of P erl, s ome queries to the Flic kr A P I , and s ome


s c reen- s c raping, you c an c reate an arc hive of your c omments .
With the c onvers ations s tored on your own hard drive, you c an
s earc h them and refer bac k to them as muc h as you'd like.

The Code

U nfortunately, Flic kr does n't give ac c es s to c omments via its


A P I , s o this c ode relies on s creen-s crapingdownloading the
H T M L of the relevant pages and pic king through it with regular
expres s ions to gather c omments . Sc reen- s c raping is a
notorious ly brittle proc es s . Keep in mind that if Flic kr c hanges
the H T M L of its pages even s lightly, this c ode will no longer
work.

You'll need s everal P erl modules ins talled on your s ys tem for
this s c ript to work. Flickr::API
(http://s earc h.c pan.org/~iamc al/Flic kr- A P I -
0 .0 7 /lib/Flic kr/A P I .pm) is us ed to find a lis t of photos for a given
us er, and XML::Simple (http://s earc h.c pan.org/~grantm/XM L-
Simple- 2 .1 4 /lib/XM L /Simple.pm) pars es through the A P I
res pons e. LWP::Simple (http://s earc h.c pan.org/~gaas /libwww-
perl- 5 .8 0 3 /lib/LWP /Simple.pm) grabs the H T M L at Flic kr to
s c rape c omments for a s pec ific photo.

To get s tarted, c reate a file c alled comments -backup.pl and add


the following c ode. Be s ure to inc lude your own Flic kr N SI D and
A P I key (available at http://www.flic kr.c om/s ervic es /api/). You'll
als o want to s pec ify a direc tory in whic h to s tore the bac kups . I n
this example, the direc tory is s et to the loc al folder flickr-
comments , but you c an c hange this to any loc ation.

#!/usr/bin/perl
# comments-backup.pl
# Creates a text file for each photo with comments
# at Flickr, and saves the comments to the file
#
# You can get an API key, find your NSID, and read the
# full documentation for the Flickr API at:
#
# http://www.flickr.com/services/api/

use strict;
use Flickr::API;
use Flickr::API::Response;
use LWP::Simple;
use XML::Simple;

# Set your variables


my $nsid = 'insert your NSID';
my $api_key = 'insert your API key';
my $dir = "flickr-comments";

# Create the directory if necessary


unless (-d $dir) { mkdir($dir); }

# Start the API


my $api = new Flickr::API({'key' => $api_key});

# Get a list of photos


my $response = $api->execute_method('flickr.people.getPublicPhotos
'user_id' => $nsid,
'per_page' => 500,
'extras' => 'date_taken'});

# Parse the XML


my $xmlsimple = XML::Simple->new( );
my $flickr_xml = $xmlsimple->XMLin($response->{_content});
my $photolist = $flickr_xml->{photos}->{photo};

# Sort the hash numerically, with largest IDs first


my @photos = sort { $b <=> $a } keys %{$photolist};

# Loop through the items returned, adding as items to feed


foreach my $id (@photos) {
my $secret = $photolist->{$id}->{secret};
my $server = $photolist->{$id}->{server};
my $owner = $photolist->{$id}->{owner};
my $username = $photolist->{$id}->{username};
my $title = $photolist->{$id}->{title};
my $datetaken = $photolist->{$id}->{datetaken};
my $img_src = "http://static.flickr.com/$server/$id\_$secret.jp
my $img_tag = "&lt;img src=\"$img_src\" /&gt;";
my $link = "http://www.flickr.com/photos/$owner/$id/";

my $page = get($link);
if ($page =~ m!<h3>Comments</h3>!mgis) {
print "Backing up comments for photo $id: $title\n";
my $section;
my $file = "$dir$id.txt";
open FILE, ">$file" or warn "Can't open $file\n";
print FILE "$title\n$datetaken\n$link\n\n";
($section) = $page =~ m!<h3>Comments</h3>(.*?)</table>!s;
while ($section =~ m!<tr valign="top">.*?<h4>(.*?)</h4>.*?<p
my $commenter = $1;
my $comment = $2;
$comment =~ s!<.+?>!!gs;
($commenter) = $commenter =~ m!<a href.*?>(.*?)</a>!gis;
print FILE "$commenter: $comment\n";
}
print FILE "\n\n";
close FILE;
}
}
O nc e the s c ript has a lis t of photos , it downloads eac h photo's
detail page from Flic kr and extrac ts any c omments with regular
expres s ions . For eac h photo that has c omments , the s c ript
c reates a text file with the photo I D and adds to it the title, date,
U RL , and, of c ours e, c omments .

Running the Hack

To s tart your bac kup, run the s c ript from a c ommand prompt like
this :

perl comments-backup.pl

T he s c ript will report its ac tivity as it goes along, indic ating


whic h photos it's c reating text files for. I n the end, you s hould
have one text file in your s pec ified bac kup direc tory for eac h of
your P ublic photos on Flic kr that has c omments . Figure 5 - 4
s hows the bac kup text file for the c onvers ation pic tured in Figure
5 -3 .

Figure 5-4. Flickr comments backup file


T hes e text files aren't a partic ularly s truc tured format for the
data, but the s c ript s hould be eas y to tweak if you'd rather s tore
the bac kups as XM L or C V S. A more s truc tured format c ould be
helpful if you plan to import them into a databas e, for example.

Hacking the Hack

O ne of the big advantages of having loc al c opies of your


c onvers ations on Flic kr is the ability to s earc h them. I n our
example, for ins tanc e, if you c ouldn't quite remember where
thos e other c overed bridges were you c ould s earc h for mentions
of the phras e "c overed bridge" to find relevant matc hes .

G oogle D es ktop Searc h (http://des ktop.google.c om) does a fine


job of s earc hing through loc al files for s pec ific phras es . Figure
5 - 5 s hows the res ults of a G oogle D es ktop Searc h for the
phras e "c overed bridge," whic h has turned up the Flic kr
c omments bac kup file.

Figure 5-5. Google Desktop Search results


C lic k the file to s ee the full c onvers ation; to s ee it in its original
c ontext, c opy the U RL in the file and pas te it into your brows er's
addres s bar.

Bac king up c omments is n't a nec es s ity, but if you want to know
that your c omments are going to be available for years to
c omeand give yours elf the ability to s earc h through themyou
might want to try it.
Hack 32. Make a Contact Sheet

You want to see your photos. Lots of them. In an attractive


grid. But how do you do it?

P eople have lots of names for thes e things : c ontac t s heets ,


proofs , galleries , enormous grids of doom. Bas ic ally, we're
talking about a bunc h of photos , all on one page. T here are a
number of ways to produc e this res ult:

Photo-management s oftware

C hanc es are, the s oftware that c ame with your digital


c amera or the s oftware you us e to manage your photos
on your c omputer has a feature to produc e c ontac t
s heets . I n P ic as s a, for example, this feature is available
on the folder menu as P rint C ontac t Sheet. But if you
want to print a c ontac t s heet of Flic kr photos tagged with
bunnies , whic h don't nec es s arily res ide on your hard
drive (yet), this s olution might not s eem ideal.

QOOP

T he Q O O P photo printing s ervic e has a s ervic e geared


toward Flic kr us ers
(http://www.qoop.c om/photobooks /flic kr_us er/). Q O O P
will print books or pos ters c ontaining hundreds of photos
and s hip to them to you for a pretty reas onable pric e.
T his is a good way to produc e gift books , or to impres s
the folks s itting at your c offee table.

I mageMagick

I mageM agic k (http://www.imagemagic k.org) is a free


s uite of image- proc es s ing s oftware that c omes with a
s et of powerful c ommand- line applic ations . T hes e apps
will let you s lic e and dic e photos to your heart's c ontent.
T he s oftware is available as a binary ins tall for Windows ,
M ac O S X, and mos t flavors of U nix/L inux.

T he mos t flexible of the three options is I mageM agic k. O ther


hac ks in this book, s uc h as [Hack #44], s how how to us e the
I mageM agic k A P I with your favorite s c ripting language (okay,
my favorite s c ripting language), P erl, to produc e s tunning
mos aic s and c ollages , but you c an us e I mageM agic k to build a
c ontac t s heet without any s c ripting at all.

I mageM agic k c omes with a large c ollec tion of powerful


c ommand- line tools . H ere are the two that I us e the mos t:

convert

C onverts between image formats , s uc h as P N G , G I F, or


J P G . You c an als o us e it to res ize photos , blur or
s harpen them, c rop them, perform nois e reduc tion, and
do many other things that you might otherwis e do with a
program s uc h as P hotos hop or G imp.

montage
O ffers various options for c ompos iting multiple images
together into a s ingle large image. I t makes a great all-
purpos e c ontac t s heet generator.

What You Need

You'll need a c ouple of things for this hac k:

I mageMagick

You c an download I mageM agic k from


http://www.imagemagic k.org/s c ript/binary- releas es .php;
binary releas es are available for all the major platforms .
You'll als o need to ins tall P erlM agic k, the I mageM agic k
A P I for P erl.

Photos lots of `em

You c an us e the downloading s c ripts developed in [Hack


#34]] to grab the photos you're interes ted in. With thes e
s c ripts in plac e, you c an get a bunc h of pic tures of
bunnies by typing the following c ommands .

T his c ommand will produc e a text file named bunnies .ph


that c ontains a lis t of all the images tagged with
bunnies :

$ getPhotoList.pl bunnies
T his c ommand downloads all the images in the
bunnies .ph file and puts them into a s imilarly named
direc tory:

$ getSnaps.pl bunnies

Running the Hack

G et to the c ommand line and c hange direc tory (cd) to where your
images res ide. T hen invoke the montage c ommand, as follows :

$ montage *.jpg montage.png

I f the direc tory in whic h you've invoked the c ommand c ontains a


few hundred very large images , go out for doughnuts (or maybe a
new C P U ). When you get bac k, you'll find a new image file
(montage.j pg) waiting for you that looks like Figure 5 - 6 .

Figure 5-6. A contact sheet made with the


montage command
I n the above example, the .png extens ion is us ed to s pec ify the
output file, giving it the P N G file format. You c an als o us e .j pg
(J P E G ), .gif (G I F), .tif (T I FF), and many other extens ions . I
prefer P N G for two reas ons : it is a los s les s format that looks
nic e, and it prevents the montage output from having the s ame
extens ion as the J P E G images I 'm working with. T his way, I c an
c ontinue to us e *.jpg to c reate new montages without
ac c identally inc orporating the previous montage images .

Be s ure to s pec ify an explic it output image


name on the c ommand line! T he las t
image name you s pec ify is as s umed to be
the output image, and it's a little too eas y
to ac c identally overwrite one of your input
images by ac c identally omitting this
parameter.

Hacking the Hack

T he montage c ommand has a huge amount of options for tweaking


the output. I f you enter the c ommand montage, without any
arguments , it'll s pit out the following lis t (or you c an read about
them at http://www.imagemagic k.org/s c ript/montage.php):

-adjoin join images into a single multi-image file


-affine matrix affine transform matrix
-authenticate value decrypt image with this password
-blue-primary point chromaticity blue primary point
-blur factor apply a filter to blur the image
-border geometry surround image with a border of color
-channel type Red, Green, Blue, Opacity, Index, Cyan, Yel
Magenta, Black, or All
-clone index clone an image
-colors value preferred number of colors in the image
-colorspace type alternate image colorsapce
-comment string annotate image with comment
-compose operator composite operator
-compress type image compression type
-crop geometry preferred size and location of the cropped
-debug events display copious debugging information
-define format:option
define one or more image format options
-density geometry horizontal and vertical density of the imag
-depth value image depth
-display server query font from this X server
-dispose method Undefined, None, Background, Previous
-dither apply Floyd/Steinberg error diffusion to im
-draw string annotate the image with a graphic primitive
-encoding type text encoding type
-endian type LSB or MSB
-extract geometry extract area from image
-fill color color to use when filling a graphic primiti
-filter type use this filter when resizing an image
-flip flip image in the vertical direction
-flop flop image in the horizontal direction
-frame geometry surround image with an ornamental border
-gamma value level of gamma correction
-geometry geometry preferred tile and border sizes
-gravity direction which direction to gravitate towards
-green-primary point chromaticity green primary point
-interlace type None, Line, Plane, or Partition
-help print program options
-label name assign a label to an image
-limit type value Area, Disk, Map, or Memory resource limit
-log format format of debugging information
-matte store matte channel if the image has one
-mode type Frame, Unframe, or Concatenate
-monochrome transform image to black and white
-page geometry size and location of an image canvas (setti
-pointsize value font point size
-profile filename add, delete, or apply an image profile
-quality value JPEG/MIFF/PNG compression level
-red-primary point chromaticity red primary point
-repage geometry size and location of an image canvas (opera
-resize geometry resize the image
-rotate degrees apply Paeth rotation to the image
-sampling-factor geometry
horizontal and vertical sampling factor
-scenes range image scene range
-shadow add a shadow beneath a tile to simulate dep
-size geometry width and height of image
-strip strip image of all profiles and comments
-stroke color color to use when stroking a graphic primit
-support factor resize support: > 1.0 is blurry, < 1.0 is s
-texture filename name of texture to tile onto the image back
-thumbnail geometry create a thumbnail of the image
-tile geometry number of tiles per row and column
-transform affine transform image
-transparent color make this color transparent within the imag
-treedepth value color tree depth
-trim trim image edges
-type type image type
-verbose print detailed information about the image
-version print version information
-virtual-pixel method
Constant, Edge, Mirror, or Tile
-white-point point chromaticity white point
H ere are a few of the more us eful options in ac tion.

T his produc es a montage with a s ky- blue bac kground c olor:

montage -background #87CEEB *.jpg montage.png

T his does the s ame thing:

montage -background SkyBlue *.jpg montage.png

For a lis t of c olor names that I mageM agic k


rec ognizes , c hec k the table on this page:
http://www.imagemagic k.org/s c ript/c olor.php.

T his produc es a montage with only three tiles per row, ins tead of
the default five:

montage -tile 3 *.jpg montage.png


T his c ommand inc ludes the filename beneath eac h image and
res izes eac h image to 2 0 0 pixels on the longes t s ide:

montage -label %f -size 200 *.jpg montage.png

T his gives eac h c olor a two- pixel blac k border:

montage -border 2 -bordercolor black *.jpg montage4.jpg

T his one is jus t plain annoying:

montage -blur 5 -rotate 45 -border 5 -bordercolor DeepPink *.jpg m

Try it and s ee. O f c ours e, for a tool to be truly us eful, it als o has
to have the potential to be truly annoying.

I f you enter the filenames s eparately, you c an add individual


options for eac h file. T his allows you to rotate s pec ific images
that are flopped over, or give them other s pec ial treatments ,
s uc h as individual border highlights .

See Also

[Hack #34]
[Hack #43]

[Hack #49]
Hack 33. Download a List of Photos

Obtaining a list of photos is the f irst step in many projects.

I f you poke around Flic kr for more than a few minutes , one thing
bec omes evident: there are a lot of photos on the s ite. When I
firs t joined the Squared C irc le group, there were nearly 3 ,0 0 0
photographs of c irc ular objec ts in the group pool. A t the time of
this writing, the number is over 2 0 ,0 0 0 . T he Flowers group has
over 5 0 ,0 0 0 photos . Some prolific photographers , s uc h as
Fubuki, have uploaded over 1 0 ,0 0 0 of their own photos . A nd
then there are the tags . A t this moment, there are approximately
2 ,3 0 0 photos that c ontain the tag pie; 2 1 ,0 0 0 photos that
c ontain the tag apple; and 1 1 1 ,0 0 0 photos that c ontain the tag
s uns et.

A s a human with a limited c apac ity to proc es s information, thes e


numbers are overwhelming. Few people have the time, patienc e,
or mental energy to wade through the entire group pool of one of
the larger groups or more popular tags , and mos t people don't
bother.

Flic kr provides various means to help you find the good s tuff,
s uc h as the "interes tingnes s " feature, but as a hac ker, it's fun to
us e s ilic on to c runc h the photos up and s pit them out in various
ways . We'll s tart with a s et of P erl s c ripts for downloading lis ts of
photos . T hes e are bas ic workhors e s c ripts that I us e all the
time, in c onjunc tion with other s c ripts that operate on thes e lis ts
of photos .
I t might be tempting to try to build a big monolithic applic ation
that does everything you might pos s ibly want to do with Flic kr,
but I 've found it s impler and more flexible to work with a s et of
s mall modular c ommand- line s c ripts that are des igned to work
together. T his is the s ame philos ophy us ed to build many of the
c ommand- line utilities in U nix. I f you're c omfortable with the
c ommand line, you'll like this approac h.

Useful API Methods

M any Flic kr A P I methods (dis c us s ed in C hapter 6 ) return lis ts


of photos . T hes e methods inc lude:

flickr.photos.search

Returns a lis t of photos matc hing a tag or other s earc h


c riteria.

flickr.people.getPublicPhotos

Returns a lis t of P ublic photos belonging to a partic ular


pers on. N ote that if you wis h to filter thes e photos by a
partic ular tag, flickr.photos.search is more appropriate.

flickr.groups.pools.getPhotos

Returns a lis t of the photos in a group pool.

For eac h of thes e methods , the data returned looks pretty


s imilar. H ere is a typic al res ult from flickr.photos.search, in
whic h I s earc hed for photos matc hing the tags zipper and ride:

<rsp stat="ok">
<photos page="1" pages="1" perpage="100" total="7">
<photo id="41865069" owner="26084283@N00" secret="ccb3eed603" serv
<photo id="40147327" owner="28226466@N00" secret="2388324058" serv
<photo id="35777919" owner="43091440@N00" secret="78cd0de7c7" serv
<photo id="33824150" owner="10202855@N00" secret="6368d0a654" serv
<photo id="33824088" owner="10202855@N00" secret="1aeed42f5f" serv
<photo id="24152735" owner="35294562@N00" secret="b3766cfdd7" serv
<photo id="1465720" owner="44146188@N00" secret="2d5487bbe5" serve
</photos>
</rsp>

I produc ed this lis t by us ing Flic kr's A P I


E xplorer. You c an find the A P I E xplorer for
any Flic kr A P I method by going to
http://www.flic kr.c om/s ervic es /api/ and
c lic king on the name of the method you are
interes ted in. A t the bottom of the page
des c ribing the method is an A P I E xplorer
link. T he A P I E xplorer is a web- bas ed app
in whic h you c an enter parameters for the
A P I method and view the XM L res ults a
great way to familiarize yours elf with eac h
A P I method. I n this c as e, I entered
zipper,ride in the tags field and s et
tag_mode to all.
For eac h photo, the following fields are provided:

photo_id

A unique I D s tring for trac king the photo. Flic kr


repres ents thes e as 6 4 - bit integers , but you s hould
treat them as s trings , in c as e the format c hanges .

secret

A hexadec imal s tring us ed to c ons truc t U RL s to the


photo.

server

T he s erver or direc tory on/in whic h the photo res ides


(als o us ed to c ons truc t U RL s to the photo).

owner

T he user_id of the pers on who uploaded the photo.

title

T he photo's title.
ispublic

I ndic ates whether the photo is vis ible to the general


public .

isfriend and isfamily

I ndic ate whether the photo is vis ible to friends or family


members on the owner's c ontac t lis t. I f the photo is
marked as P ublic (ispublic="1 "), thes e s ettings are
irrelevant.

T he fields I am us ually the mos t


interes ted in are photo_id, secret, and
server. A s you'll s ee in [Hack #34], thes e
fields provide the information you need to
c ons truc t a U RL to the photo, s o you c an
download the image its elf.

For you to be able to ac c es s the photo, either ispublic mus t be


s et or you mus t be on the owner's friend or family lis t (and the
c orres ponding bit mus t be s et on the photo). M os t of the
methods mentioned earlier return lis ts of P ublic photos only, s o
us ually ispublic will be on.
What You Need

To talk to the Flic kr A P I , you'll need an A P I key and its


as s oc iated s hared s ec ret. I f you don't already have one, you c an
apply for an A P I key at
http://www.flic kr.c om/s ervic es /api/key.gne (s ee "A P I Keys and
Sec rets " in C hapter 6 for more information).

T he P erl s c ripts in this hac k require that you have ac c es s to


P erl on the c ommand line (M ac O S X s hips with P erl ins talled;
Windows us ers might have to download A c tiveP erl from
http://www.ac tives tate.c om/P roduc ts /A c tiveP erl/). T he s c ripts
make us e of the following public ly available modules :
Flickr::API

T his is an interfac e to the Flic kr A P I for P erl, written by C al


H enders on, one of Flic kr's employees . I t is a s ubc las s of
LWP::UserAgent. You c an find it at
http://s earc h.c pan.org/~iamc al/Flic kr- A P I /.

XML::Simple

A lthough Flickr::API performs XM L pars ing, it us es the


XML::Parser::Lite::Tree pars er, whic h produc es a data s truc ture
that c an be needles s ly c umbers ome to pars e. Fortunately, it als o
retains the data as a raw s tring, s o you c an us e any of the
myriad XM L pars ers available for P erl. I prefer the s impler data
s truc tures produc ed by XML::Simple.
Data::Dumper

T hes e s c ripts produc e output in the form of a text file that c an


be pars ed by other P erl s c ripts . A n eas y way to ac c omplis h this
is to build up the data s truc ture in P erl and then us e Data::Dumper
to dump it out into a text file. Data::Dumper is als o a great tool for
exploring the data returned by all the Flic kr A P I methods .

I f you're mis s ing any of thes e modules , you c an ins tall eac h of
them from C P A N , like this :

perl -MCPAN -e shell


cpan> install
package name

I n Windows , partic ularly with A c tiveState P erl, it is eas ier to us e


the ppm utility. For example:

ppm install
package name

With the modules in plac e, you're ready to move on to the s c ript.

The Code

C reate a file c alled getPhotoLis t.pl and type or pas te in the


following c ode:

#!/usr/bin/perl -s
#
# getPhotoList.pl - Jim Bumgardner
#

use Flickr::API;
use XML::Simple;
use Data::Dumper;
$Data::Dumper::Terse = 1; # avoids $VAR1 = * ; in dumper output
$Data::Dumper::Indent = $verbose? 1 : 0; # more concise output

# You will need to create this file...


# it supplies the authentication-related vars
# $api_key and $sharedsecret
require 'apikey.ph';

print "verbose = $verbose\n" if $verbose;

$syntax = <<EOT;

getPhotoList.pl [options] <tags> [<tags...>]


getPhotoList.pl [options] -g group_id [<tag>]
getPhotoList.pl [options] -u username [<tags>]

Options:
-all Photos must match all tags (tag search only)
-recent=X Only provide photos posted within the last X days (ta
-limit=X Provide no more than X photos
-license=X Provide photos with license X
EOT

die $syntax if @ARGV == 0;

my $api = new Flickr::API({'key' => $api_key, secret => $sharedsec

# determine method to use


$method = 'flickr.photos.search';
if ($g) {
$group_id = shift;
$tags = shift;
$method = 'flickr.groups.pools.getPhotos';
print "Searching for photos in group $group_id\n";
# determine output filename
$ofname = $group_id . '.ph';
}
elsif ($u) {
$username = shift;
$tags = join ',', @ARGV;
$method = 'flickr.people.getPublicPhotos' if !$tags;
print "Searching for photos by user $username using $method\n";
# determine output filename
$ofname = $username;
$ofname .= '_' . $tags if $tags;
$ofname =~ s/,\s*/_/g;
$ofname .= '.ph';
}
else {
$tags = join ',', @ARGV;
print "Searching for photos with tags=$tags ...\n";
# determine output filename
$ofname = $tags . '.ph';
$ofname =~ s/,\s*/_/g;
}

$nbrPages = 0;
$photoIdx = 0;

$limit = 5000 if $limit;

open (OFILE, ">$ofname");

print OFILE "\@photos = (\n";

$user_id = '';
$min_taken_date = '';
$max_taken_date = '';

$xmlp = new XML::Simple ( );

if ($recent)
{
die "-recent option only valid for tag search\n" if $method ne '
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
gmtime(time - $recent*24*60*60);
$min_taken_date = sprintf "%04d-%02d-%02d 00:00:00",1900+$year,$
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
gmtime(time);
$max_taken_date = sprintf "%04d-%02d-%02d 00:00:00",1900+$year,$
}

if ($username)
{
# look up user ID if a username was provided
#
my $response = $api->execute_method('flickr.people.findByUsernam
username => $username} );
die "Problem determining user_id: $response->{error_message}\n"

print Dumper($response) if $verbose; # explore results of call

my $xm = $xmlp->XMLin($response->{_content});
$user_id = $xm->{user}->{id};
print "Userid: $user_id\n";
}

do
{
my $params = { per_page => 500,
page => $nbrPages+1};
$params->{tags} = $tags if $tags;
$params->{user_id} = $user_id if $user_id;
$params->{group_id} = $group_id if $group_id;
$params->{min_taken_date} = $min_taken_date if $min_taken_date;
$params->{max_taken_date} = $max_taken_date if $max_taken_date;
$params->{license} = $license if $license;
$params->{extras} = $extras if $extras;
$params->{tag_mode} = 'all' if $all;

my $response = $api->execute_method($method, $params );


die "Problem: $response->{error_message}\n" if !$response->{succ

print Dumper($response) if $verbose; # explore results of call

my $xm = $xmlp->XMLin($response->{_content},forcearray=>['photo'

$photos = $xm->{photos};
print "Page $photos->{page} of $photos->{pages}\n";

# loop thru photos


$photoList = $xm->{photos}->{photo};
foreach $id (keys %{$photoList})
{
my $photo = $photoList->{$id};
$photo->{id} = $id;
print OFILE ($photoIdx++? ",\n" : "") . Dumper($photo);
}
++$nbrPages;
} while ($photos->{page} < $photos->{pages} && (!$limit || $photoI

print OFILE "\n);\n1;\n";


close OFILE;

print "$photoIdx photos found matching tags $tags written to $ofna


A ls o c reate a file c alled apikey.ph, and add c ode like the
following:

$api_key = '12345';
$sharedsecret = '6789';

Replac e 12345 with your ac tual A P I key, and replac e 6789 with
your ac tual s hared s ec ret. (See C hapter 6 for more information
on A P I keys and s hared s ec rets .)

Running the Hack

To tes t the s c ript, try running the following c ommand:

getPhotoList.pl aardvark

T his will produc e a file c alled aardvark.ph, whic h c ontains a lis t of


the photos matc hing the tag aardvark. T he firs t few lines read as
follows :

@photos = (
{ 'owner' => '24512271@N00', 'isfriend' => '0', 'ispublic' => '1',
'title' => 'Groupportrait', 'server' => '3', 'id' => '5024662', 'i
{ 'owner' => '66208233@N00', 'isfriend' => '0', 'ispublic' => '1',
'title' => 'Grooming is important', 'server' => '8', 'id' => '1199
{ 'owner' => '44124388719@N01', 'isfriend' => '1', 'ispublic' => '
'title' => 'The Night Visitor', 'server' => '4', 'id' => '5043567'
{ 'owner' => '66208233@N00', 'isfriend' => '0', 'ispublic' => '1',
'title' => 'Buffy_close', 'server' => '7', 'id' => '6883675', 'isf
...

To us e the s c ript with multiple tags , s eparate the tags with


s pac es , like s o:

getPhotoList.pl rose americanbeauty

I f you want to require that eac h photo matc h all the tags , us e the
optional -all argument.

getPhotoList.pl -all rose americanbeauty

I f you don't provide the -all argument, the s c ript defaults to


doing an O R- s tyle s earc h (i.e., photos matc hing any of the tags
will be returned).

To get all of Fubuki's photos , us e the -u (us er) option, like s o:

getPhotoList.pl -u fubuki

A dd additional arguments to res tric t Fubuki's photos to thos e


matc hing a partic ular tag or s et of tags . To produc e a lis t of
Fubuki's photos that c ontain the tag macro, us e this c ommand:
getPhotoList.pl -u fubuki macro

To produc e a lis t of photos that are in a group pool, you'll need to


determine the group_id. You c an get the I D s of the groups you
belong to by c alling the flickr.groups.pools.getGroups method or
from the Flic kr A P I E xplorer web page, loc ated at
http://www.flic kr.c om/s ervic es /api/explore/?
method=flic kr.groups .pools .getG roups .

O nc e you know the group_id, us e the s c ript with the -g (group)


option, like s o:

getPhotoList.pl -g
group_id

O ther s c ripts des c ribed in this book c an us e the files produc ed


by this s c ript. For example, to download a c ac he of Fubuki's
images , us e the s c ript in c onjunc tion with the getSnaps .pl s c ript
from [Hack #34], like s o:

getPhotoList.pl -u fubuki
getSnaps.pl fubuki

T he firs t c ommand downloads a lis t of Fubuki's photos and


s aves the information to the file fubuki.ph. T he s ec ond c ommand
downloads thumbnail vers ions of eac h of the photos .

O ther hac ks in this book demons trate how to us e thes e lis ts for
projec ts that involve large- s c ale image manipulation, s uc h as
photo mos aic s [Hack #49] or c olor pic kers [Hack #45] .

To us e one of thes e photolis t files in your own P erl s c ripts , get


the filename from the c ommand line and then require it, like s o:

$photoList = shift;
require "$photoList";

M y own s c ripts us ually automatic ally add the .ph extens ion if it
has n't already been provided:

$photoList = shift;
$photolist .= '.ph' if !($photolist =~ m/\./);
require "$photoList";

H ere's a bas ic loop that walks through the images and c onverts
them into U RL s to thumbnails :

$suffix = "_t"; # thumbnail suffix


foreach $photo (@photos)
{
sprintf "http://static.flickr.com/%d/%d_%s%s.jpg",
$photo->{server},$photo->{id}, $photo->{secret}, $suffix;
}

Finally, here's a little s c ript, getSnap.pl, that will download one of


the photos c ontained in one of thes e lis ts :

#!/usr/bin/perl
use LWP::Simple;

$photolist = shift;
$photolist .= '.ph' if !($photolist =~ m/\./);
$photo_id = shift;
die "getSnap.pl [photolist_file] [photo_id#]\n" if !$photo_id;

require "$photolist";

foreach $p (@photos)
{
if ($p->{id} eq $photo_id)
{
$photo = $p;
last;
}
}

die "image $photo_id not found in $photolist.\n" if !$photo;

$purl = sprintf "http://static.flickr.com/%d/%d_%s.jpg", $photo->{


$pimg = get $purl;
$fname = "${photo_id}.jpg";
open (OFILE, ">$fname ") || die ("can't open $fname\n");
binmode OFILE;
print OFILE $pimg;
close OFILE;

See [Hack #34] for a way to download all of them more


effic iently.
See Also

[Hack #34]

[Hack #43]

[Hack #49]
Hack 34. Cache Photos Locally

Flickr has tons of photos, but your hard drive is f aster.

I f you're working on a projec t that involves large numbers of


Flic kr photos , s uc h as a mos aic [Hack #49], you will probably
want to make loc al c opies of the photos on your hard drive.
Reading photos loc ally is muc h fas ter than downloading them
from Flic kr. I find that my s c ripts might download medium- s ized
photos as s lowly as one per s ec ond, but they c an proc es s
hundreds per s ec ond when reading them off my hard drive. I f you
end up running your s c ript more than onc e, this hac k will s ave
you a huge amount of time.

When downloading photos from Flic kr, pleas e be a good Flic kr


c itizen and follow thes e guidelines :

D on't download photos that are larger than you need. For
mos t of my projec ts , I require only s mall thumbnail
images . T hes e download fas ter from Flic kr and put les s
of a s train on their s ervers .

D on't download more photos than you need. I f you are


interes ted only in photos of lighthous es , don't download
every s ingle photo pos ted to Flic kr C entral. U s e the
various filtering options in the flic kr.photos .s earc h A P I
method [Hack #33] to identify jus t the images you need.
Constructing Flickr URLs

D ownloading photos from Flic kr involves taking the following


three identifying fields that Flic kr as s oc iates with eac h photo
and c onverting them into a U RL :

photo_id

T his is a unique number as s oc iated with the photo.


Flic kr s tores this internally as a 6 4 - bit integer, but you
might want to treat it as a s tring, in c as e Flic kr c hanges
the format in the future.

secret

T his is a hexadec imal s tring that mus t be inc orporated


into the U RL to obtain the photo. Sec rets are not
nec es s arily unique, but eac h photo_id has one and only
one secret.

server

To handle the enormous load, Flic kr divides the photos


among a number of s ervers , eac h of whic h has a number.
E ac h photo is as s igned a server number when it is firs t
uploaded to Flic kr.

T he photos thems elves c an be ac c es s ed us ing one of the


following U RL s ys tems :
http://static.flickr.com/<server>/<photo_id>_<secret>.jpg
http://static.flickr.com/<server>/<photo_id>_<secret>_<size>.jpg

I f the <size> qualifier is left out, as in the firs t variant, you'll get
a medium- s ized vers ion of the image, whic h is 5 0 0 pixels on the
longes t s ide. T his is the vers ion people s ee on the photo's detail
page.

T he following values are available for the <size> qualifier:

Small s quare7 5 x 7 5 pixels

T humbnail1 0 0 pixels on the longes t s ide

Small2 4 0 pixels on the longes t s ide

No qualifier

M edium5 0 0 pixels on the longes t s ide (this is the


default s etting)
b

L arge1 0 2 4 pixels on the longes t s ide (exis ts only for


very large original images )

O riginaloriginal dimens ions ; either a J P E G , G I F, or P N G ,


depending on the s ourc e format (the vas t majority are
JP E Gs )

For example, c ons ider a photo with the following information:

photo_id 3263379

secret 21ee6ccacf

secret 3

You c ould ac c es s this photo us ing any of the following U RL s :

http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f.jpg


http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f_s .jpg
http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f_t.jpg
http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f_m.jpg
http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f_b.jpg
http://s tatic .flic kr.c om/3 /3 2 6 3 3 7 9 _2 1 ee6 c c ac f_o.jpg

(A lthough, as it turns out, the U RL with the b value for <size>


does n't work, bec aus e the original photo is only 7 0 0 pixels
ac ros s .)

What You Need

T he P erl s c ripts in this hac k require you to have ac c es s to P erl


on the c ommand line and make us e of the public ly available
LWP::Simple module. T his module enables you to retrieve data
from a web s ite by is s uing a s imple get( ) c ommand.

I f you're mis s ing the LWP::Simple module, you c an ins tall it from
C P A N , like this :

perl -MCPAN -e shell


cpan> install LWP::Simple

T he P erl s c ripts in this hac k als o require that you have the
getPhotoLis t.pl s c ript from [Hack #33] .

The Code

C reate a file c alled getSnaps .pl and enter the following c ode into
it:
#!/usr/bin/perl -s

# getSnaps.pl - Jim Bumgardner


#
# grab tagged photos and put small thumbnails into a named folder
#
# use -med option for medium-sized photos

use LWP::Simple;

$photolist = shift;
$dirname = shift;
die "getSnaps.pl [-big] <photolist_file> [dirname]\n" if !$photoli

$dirname = $photolist if !$dirname;


$dirname =~ s/\.ph// if $dirname =~ /\.ph$/;
$photolist .= '.ph' if !($photolist =~ /\./);

require "$photolist";

$nbrAdded = 0;

if (!(-e $dirname))
{
print "Making directory $dirname\n";
`mkdir $dirname`;
}

$suffix = $big? '' : '_t';

foreach $photo (@photos)


{
$purlt = sprintf "http://static.flickr.com/%d/%d_%s%s.jpg",
$photo->{server},$photo->{id}, $photo->{secret}, $
$fnam = "$dirname/$photo->{id}$suffix.jpg";

$hasSmall = 0;

print "Checking $fnam...\n" if $verbose;

# printf "Checking $fnam...\n";


if (!(-e $fnam))
{
print "Adding $fnam...\n";
foreach (0..5)
{
$pimg = get $purlt;
last if $pimg;
print "Retry...\n";
sleep 1;
}
die "Couldn't get image $purlt\n" if !$pimg;
open (OFILE, ">$fnam") || die ("can't open $fnam\n");
binmode OFILE;
print OFILE $pimg;
close OFILE;
print "$nbrAdded...\n" if ++$nbrAdded % 50 == 0;
}
}

print "$nbrAdded added\n";

Running the Hack


To us e this c ode, you'll need the getPhotoLis t.pl s c ript developed
in [Hack #33] .

To download a s et of images with a partic ular tag, us e the


following c ommands :

getPhotoList.pl
tag

getSnaps.pl
tag

H ere is a s ample run:

$ getPhotoList.pl aardvark
Searching for photos with tags=aardvark ...
Page 1 of 1
31 photos found matching tags aardvark written to aardvark.ph

$ getSnaps.pl aardvark
Making directory aardvark
Adding aardvark/5024662_t.jpg...
Adding aardvark/11999049_t.jpg...
Adding aardvark/5043567_t.jpg...
(etc...)
Adding aardvark/23418439_t.jpg...
31 added

When the s ec ond s c ript is done running, you'll find a new folder
named aardvark, whic h c ontains all the thumbnails that are
referenc ed the photolis t file aardvark.ph that was c reated by the
firs t s c ript. I f you wis h to s tore the photos in a different
direc tory, s pec ify it on the c ommand line, like s o:

$ getSnaps.pl aardvark myAnimalPics

I f the direc tory does n't already exis t, the s c ript will c reate it.

Hacking the Hack

T here are two s trategies you c an us e for c ac hing images : you


c an put images us ed for a partic ular projec t into a s ingle folder,
as we did in the previous example; or you c an keep all the
images for all your projec ts in a c entral repos itory, whic h might
c ons is t of multiple folders . I us e the s ec ond method, bec aus e I
have a lot of projec ts and it puts les s s train on Flic kr; if a photo
is us ed in more than one projec t I need to download it only onc e,
whic h reduc es the amount of time I s pend downloading images
and the amount of s pac e they take up on my hard drive.

I have downloaded hundreds of thous ands photos to my loc al


c ac he, s o I have developed a s ubdivis ion s ys tem that ens ures
that no one folder holds more than a thous and photos . T his
makes it fas ter to travers e the direc tories and look at photos .
Windows , in partic ular, c an be quite s low to dis play the c ontents
of a folder c ontaining tens of thous ands of files .

M y c ac he res ides in a root folder c alled s naps . T his , in turn,


c ontains one folder for eac h Flic kr s erver (s naps /1, s naps /2,
etc .). E ac h s erver folder c ontains a s et of folders that hold up to
1 ,0 0 0 photos eac h. M y example file from server 3 with photo_id
3263379 gets the following loc al pathname:
s naps /3/3263/3263379.j pg.

I f you want to us e this c entralized s torage s trategy, replac e the


line that generates the output filename:

$fnam = "$dirname/$photo->{id}$suffix.jpg";

with this bloc k of c ode:

$rootdir = "snaps"; # make this directory ahead of time


$servdir = "$rootdir/server$photo->{server};
$kilodir = "$servdir/" . int($photo->{id}/1000);
$fnam = "$kilodir/$photo->{id}$suffix.jpg";

T his c ons truc ts the (more c omplic ated) path to the file, and
makes the s ubdirec tories , if nec es s ary.

Before c reating the file, you s hould make the direc tories leading
up to the file, if nec es s ary, like s o:

`mkdir $rootdir` if !(-e $rootdir);


`mkdir $servdir` if !(-e $servdir);
`mkdir $kilodir` if !(-e $kilodir);

I f you keep downloading photos , you'll eventually build up a huge


loc al c ac he, whic h you c an us e as s ourc e material for giant
photo c ollages and the other impres s ive projec ts in the hac ks to
c ome.
See Also

[Hack #33]

[Hack #43]

[Hack #45]

[Hack #49]
Hack 35. Edit Photos as a Batch

Make changes to your photos en masse with batch editing.

O ften, when you're brows ing around Flic kr you'll notic e a way
that s omeone els e is us ing tags that you c ould apply to your own
photos . For example, you might have tagged s everal of your
photos taken in national parks with the words Yos emite or
Yellows tone, but not inc luded the tag national park.

You c ould brows e to eac h photo's detail page and add the tag
manually, or you c ould take advantage of Flic kr's batc h- editing
features to add the tag to all the relevant photos in one fell
s woop.

Batch Editing in Flickr

Batc h editing involves making a c hange to a c ollec tion of


photos . T hat c ollec tion c an be as s imple as the firs t page of your
photos tream, or a more c omplex res ult s et bas ed on a multiple-
tag s earc h. T he key to editing photos in a batc h is keeping an
eye out for the "E dit as a batc h" links .

I f you brows e to your photos tream, you'll s ee an "E dit thes e as a


batc h? " link on the right s ide of the page. C lic k the link and you
c an edit all of the photos on the firs t page of your photos tream at
onc e. You c an als o gather together a group of photos by tags .
E nter a tag (or a group of tags s eparated by c ommas ) into the
"Searc h by tag" form on your photos tream page, and you'll s ee a
lis t of res ults like thos e s hown in Figure 5 - 7 .

Figure 5-7. Tag search results with "Edit as a


batch" link
A t the top of the s earc h res ults page, you'll s ee the number of
res ults , along with a link to edit all of the photos in the res ults as
a batc h. C lic k the link to bring up the T itle/D es c riptions batc h-
editing page s hown in Figure 5 - 8 .

Figure 5-8. Batch editing titles, descriptions, and


tags
O n the T itle/D es c riptions batc h- editing page, you'll s ee eac h of
the photos in the batc h, along with a form to c hange the title,
des c ription, and tags as s oc iated with eac h of the photos . You
c an go down the lis t and make your adjus tments , s aving you the
time involved with vis iting eac h photo's detail page. C lic k Save
at the bottom of the page when you're finis hed, and all of the
photos will be updated.

I f you'd rather s imply add a tag to all of the photos , you c an


c lic k the Batc h O perations tab at the top of the page for even
more editing options , as s hown in Figure 5 - 9 .

Figure 5-9. Adding a tag to a group of photos


with batch editing
You c an add a s pec ific tag to all of the photos , c hange the
privac y s ettings , or even delete all of thes e photos from your
photos tream. (O f c ours e, deleting the photos means the photos
will no longer be available at Flic kr, s o delete with c aution! )

While thes e batc h- editing features c an handle mos t c hanges


you'll want to make, s ome ingenious Flic kr members have
extended the batc h- editing c apabilities even further with s ome
help from G reas emonkey.

Extending Batch Editing

G reas emonkey is a plug- in for the Firefox brows er that lets


us ers injec t c ode into pages . A c ouple of G reas emonkey s c ripts
add even more features to Flic kr's batc h- editing pages to enable
us ers to edit other as pec ts of photos in a group. To get s tarted,
ins tall G reas emonkey by vis iting
http://greas emonkey.mozdev.org. O nc e it's ins talled, you'll be
s et to us e the following s c ripts .

T he Flic kr Batc h O perations E nhanc er by Flic kr member L ac hie


(http://www.flic kr.c om/photos /lac hie/) adds s everal options to
the Batc h O perations page. To ins tall the s c ript, point Firefox to
http://members .iinet.net.au/~lac hiec /greas emonkey/flic k_batc h.us

C hoos e Tools I ns tall T his U s er Sc ript... from the menu,


and then reload the Batc h O perations page at Flic kr. C lic k the
Show E nhanc ements link under the s tandard options , and you'll
s ee the new options available, as s hown in Figure 5 - 1 0 .

Figure 5-10. Extended batch options with


Lachie's Greasemonkey enhancement
With the s c ript ins talled, you c an edit the date and time for eac h
photo in the batc h, adjus t the photo lic ens ing [Hack #16], and
s et extended permis s ions for eac h photo, inc luding who c an
c omment or add notes and tags .

A nother G reas emonkey s c ript, Flic kr T itle + D es c riptions Batc h


Tools by Flic kr member Steeev
(http://www.flic kr.c om/photos /s teeev/), adds s ome options to the
T itle/D es c riptions batc h- editing page. To ins tall this
G reas emonkey s c ript, brows e to
http://s teeev.f2 o.org/flic kr/flic kr.title+des c .batc h.us er.js .

G o through the s c ript addition proc es s and brows e to the Flic kr


T itle/D es c riptions batc h- editing page. You'll s ee the additions
s hown in Figure 5 - 1 1 .

Figure 5-11. Extended batch options with


Steeev's Greasemonkey script
Two new links at the top of the page let you append text to all
titles or des c riptions , s aving the time of pas ting text into eac h
field by hand. T he arrows to the right of the form fields in the firs t
entry let you s pec ify the initial field's value as the value for all
fields on the page. U s ing the arrows will delete any value that
was in the fields before, s o be s ure that you really want every
photo in the batc h to have exac tly the s ame title, des c ription,
and tags before you us e them.

U pdating more than a handful of photos does n't have to be a


c hore if you know how to us e the built- in batc h- editing tools .
A nd the Firefox/G reas emonkey c ombination c an provide even
more options for c hanging your photos quic kly.
Hack 36. Clean the (Group) Pool

Cleaning the pool is all in a day's work f or this bot.

A s moderator of s ome large groups on Flic kr, s uc h as the


Squared C irc le (http://www.flic kr.c om/groups /c irc le/) and
Flowers (http://www.flic kr.c om/groups /florus /) groups , I 've found
it helpful to make s ome power tools to as s is t with moderating
them.

I n a large group, s everal hundred new photos might be s ubmitted


to the group photo pool eac h day, s o it c an be c umbers ome for
humans to weed through them all. Furthermore, s ome
enterpris ing individuals might try to add huge batc hes of photos
to a group's photo pool all at onc e. When this happens , new
photos s ubmitted by other us ers quic kly get buried under the
avalanc he, and no one gets a c hanc e to really apprec iate them.

Some large groups deal with this problem by pos ting an upload
limit in the group des c ription, s uc h as "N o more than three
photos a day." H owever, many c ontributors either don't notic e
thes e rules , don't s peak the language they are pos ted in, or
s imply don't c are. M anually enforc ing upload limits c an be a
c hore; if there are tons of people s ubmitting photos , it's diffic ult
to keep trac k of who has s ubmitted what. A nd unfortunately,
Flic kr has no mec hanis m for limiting uploads to group pools .

T he Flic kr A P I , however, provides a method c alled


flickr.groups.pools.remove that c an be us ed as the bas is of a
group robot, or bot, des igned to do jus t that. T he bot is a s c ript,
tied to one of the group adminis trator's ac c ounts , that
automatic ally removes photos from the group pool. M y bot
H ipbot (whos e profile is s hown in Figure 5 - 1 2 ) was the firs t s uc h
pool- c leaning bot on Flic kr, and I 'm going to s hare one of the
princ ipal H ipbot s c ripts in this hac k.

Figure 5-12. Hipbot's profile


T he s c ript s c ans a c ollec tion of different groups that H ipbot
adminis ters and applies s lightly different polic ies to eac h of
thes e groups , removing photos that exc eed the s ubmis s ion
limits of eac h partic ular group.

I f you haven't us ed the Flic kr A P I before,


we s ugges t you c hec k out the firs t few
s ec tions of C hapter 6 before you get
s tarted. You may als o want to try s ome of
the hac ks in that c hapter before us ing this
s c ript.

What You Need

To run this s c ript, you'll need an API key, a s hared s ecret, and an
authorization token, as explained in [Hack #40] . T hes e
parameters will be us ed to tell the A P I that you have s uffic ient
permis s ions to delete photos from the group pool.

T his s c ript works only if you are an


adminis trator of the group or groups whos e
pool(s ) you are trying to c lean.

T his partic ular example is c onfigured for H ipbot's groups . I f you


want to us e this s c ript with your own groups , you'll need the
group I D s of the groups you are adminis trating. You c an obtain
group I D s by vis iting the A P I E xplorer page for
flickr.groups.pools.getgroups, whic h is loc ated at
http://www.flic kr.c om/s ervic es /api/explore/?
method=flic kr.groups .pools .getG roups .

C lic k the C all M ethod... button on this page to s ee a lis t of your


groups and their group I D s .

You'll als o need the Flickr::API module, whic h is available from


C P A N . T his module s implifies c ommunic ating with the Flic kr
A PI.

I f you're mis s ing this module, you c an ins tall it from C P A N , like
this :

$ perl -MCPAN -e shell


cpan> install Flickr::API

You'll als o need XML::Simple, whic h I c ommonly us e to s implify


pars ing the data s truc tures returned by Flickr::API. I ns tall it the
s ame way.
The Code

Firs t, c reate a file for s toring the authentic ation information. C all
it bot_auth.ph, and s tore the following c ode in it:

$api_key = '928c994908f02385d1d97a457003cb71';
$shared_secret = '8698bb062a08ca11';
$auth_token = '127122-92395db066e82035';
1;

I ns tead of the values s hown here, us e your own api_key,


shared_secret, and auth_token.

N ext, c reate the file for the main bot s c ript, cleanPool.pl. I 'll
des c ribe this c ode in s ec tions , s tarting with s ome bas ic s etup to
s pec ify whic h modules we are going to us e and require the
bot_auth.ph file:

#!/usr/bin/perl -s

use Flickr::API;
use XML::Simple;

require 'bot_auth.ph'; # provides api_key, shared_secret, and auth

N ext is a data s truc ture, whic h des c ribes the rules for eac h
group we are adminis trating:

@groups = (
{name=>'Flowers', id=>'13378274@N00', limit=>3,
submitWindow=>7*60*60, cutoffTime => time - 1*24*60*60},
{name=>'JPG Mag', id=>'52240402017@N01', limit=>1,
submitWindow=>7*60*60, cutoffTime => time - 1*24*60*60},
{name=>'Least Interesting', id=>'55489371@N00', limit=>1, keepN
submitWindow=>0, cutoffTime => 0},
{name=>'Your Favorites', id=>'74565724@N00', limit=>2, keepNewe
submitWindow=>0, cutoffTime => 0},
{name=>'Body Language', id=>'82402134@N00', limit=>3,
submitWindow=>12*60*60, cutoffTime => time - 1*24*60*60},
{name=>'Hand Signals', id=>'80263920@N00', limit=>3,
submitWindow=>12*60*60, cutoffTime => time - 1*24*60*60},
{name=>'Critique - Advanced',id=>'48467233@N00', limit=>0,
submitWindow=>0, cutoffTime=>0},
{name=>'Critique - For Starters',id=>'16162753@N00', limit=>0,
submitWindow=>0, cutoffTime=>0},
{name=>'Critique - Intermediate',id=>'71433669@N00', limit=>0,
submitWindow=>0, cutoffTime=>0}
);

T he Flowers group allows pos ting of a maximum of three photos


every s even hours . O ther groups , s uc h as the C ritique groups ,
allow no photos at all. T he L eas t I nteres ting group allows eac h
member to have only one photo in the pool; if a new photo is
added, the old one gets deleted. T he cutoffTime parameter is
us ed to optimize data loading, as you'll s ee later.

N ow, initialize the Flickr::API module, us ing the fields defined in


the bot_info.ph file:

# Set up the Flickr::API


#
my $api = new Flickr::API({'key' => $api_key, secret => $shared_se
T hen loop for eac h group, performing the following ac tions on
eac h group:

# loop for each group


#
foreach $group (@groups)
{
print "$group->{name}...\n";

T his is the s ame tec hnique us ed in [Hack #33], and it will


provide us with a lis t of the photos we're interes ted in. G roup
photo lis ts are s orted by order of s ubmis s ion to the group, with
the mos t rec ent photos lis ted firs t.

T he s c ript us es the cutoffTime variable to break the loop


prematurely if we s tart s eeing photos from a time period we've
already adminis tered:

# Get list of photos


#
#
@photos = ( );
$nbrPages = 0;
$photoIdx = 0;
do
{
$nbrAdded = 0;

my $response = $api->execute_method('flickr.groups.pools.getPh
group_id => $group->{id},
per_page => 500,
page => $nbrPages+1}
);

my $xml = $response->{_content};
$xml =~ s/ownername="[^"]+"//g; # Get rid of stuff that
$xml =~ s/title="[^"]+"//g; # may causing parsing problem
$xm = XMLin($xml);
$photolist = $xm->{"photos"}->{"photo"};
$maxTime = 0;
foreach $id (keys %{$photolist})
{
$photo = $photolist->{$id};
$photo->{id} = $id;
push @photos, $photo;
$maxTime = $photo->{dateadded} if $photo->{dateadded} > $max
$photoIdx++;
$nbrAdded++;
}
print "$photoIdx...\n";
++$nbrPages;
} while ($nbrAdded > 0 && $maxTime > $group->{cutoffTime});

T he cutoffTimes variable c an be us ed only for groups that have a


"no more than N photos in N hours " rule; otherwis e, we have to
load all the photo data.

N ext, the s c ript s orts the photos by time. Some groups have a
polic y that newer s ubmis s ions s hould c aus e older s ubmis s ions
to be deleted. I n this c as e, we s ort in revers e- c hronologic al
order. O therwis e, we s ort in c hronologic al order:

# Collect photos by owner


#
%owners = ( );
@photos = sort {$a->{dateadded} <=> $b->{dateadded} } @photos;
@photos = reverse @photos if $group->{keepNewest};

T he s c ript then c ollec ts the photos that eac h pers on has


s ubmitted into a has h c alled $owners:

foreach $photo (@photos)


{
$owner = $photo->{owner};
$owners{$photo->{owner}} = {photos=>[]} if !(defined $owners{$
push @{$owners{$photo->{owner}}->{photos}}, $photo;
}

I t then walks through the $owners has h and identifies photos that
need to be rejec ted, bas ed on our rules . T he photo rec ords are
pus hed onto an array c alled @rejects:

# Select photos to reject


#
@rejects = ( );
foreach $ownid (keys %owners)
{
# print "Owner $ownid... SubmitWindow $group->{submitWindow}\
$photoList = $owners{$ownid}->{photos};
$n = 0;
foreach $photo (@{$photoList})
{
if ($n >= $group->{limit} && (!$group->{submitWindow} || abs
{
# print "$n exceeds $group->{limit} (dateadded: $photo->{
push @rejects, $photo;
}
$n++;
}
}

N ext, the s c ript rejec ts thes e photos us ing the A P I method


flickr.groups.pools.remove:

# Reject photos
#
my $totRejected = 0;
my $totGroup = @photos;
foreach $photo (@rejects)
{
print "Rejecting $photo->{id}...\n";
my $res = $api->execute_method('flickr.groups.pools.remove', {
group_id => $group->{id},
photo_id => $photo->{id}
auth_token => $auth_toke
);

if (!$res->{success})
{
print "Error rejecting $photo->{id}: $res->{error_message}\n
}
else {
$totRejected++;
}
}
T his is the only c all that requires authentic ation, s o we pas s the
authentic ation token here. A s we rejec t photos , we c ount
s uc c es s ful rejec tions .

We then s how the res ults for this group and loop onto the next
one:

# Show results
#
print "$totRejected rejected of $totGroup for group $group->{nam

# end of loop
}

A nd that's the s c ript!

Running the Hack

T his s c ript c an (and s hould) be automated to run periodic ally by


us ing a batc h s c ript or cron job, but firs t you'll probably want to
tes t it manually. H ere's a s ample run:

$ cleanPool.pl
Flowers...
500...
1000...
0 rejected of 1000 for group Flowers
JPG Mag...
499...
999...
0 rejected of 999 for group JPG Mag
Least Interesting...
500...
731...
0 rejected of 731 for group Least Interesting
Your Favorites...
500...
1000...
1500...
2000...
2500...
3000...
3101...
0 rejected of 3101 for group Your Favorites
Body Language...
500...
1000...
0 rejected of 1000 for group Body Language
Hand Signals...
277...
0 rejected of 277 for group Hand Signals
Critique - Advanced...
0...
0 rejected of 0 for group Critique - Advanced
Critique - For Starters...
0...
0 rejected of 0 for group Critique - For Starters
Critique - Intermediate...
0...
0 rejected of 0 for group Critique - Intermediate
I run this s c ript every 2 0 minutes , s o there's us ually little that
needs c leaning; indeed, in this run, nothing ac tually got deleted.

I s hould point out that tec hnic ally, this s c ript rejec ts photos that
exc eed s ome limit (s uc h as three pos tings ) in any 1 2 - hour
period. T his is not quite the s ame thing as "three per day," but it
is eas ier to detec t. Sinc e Flic kr us ers c ome from all over the
world, it's diffic ult to prec is ely define what "onc e a day" means ;
however, this method works pretty well.

To give H ipbot a little extra pers onality, I c reated a s eparate


Flic kr ac c ount for him and gave him a s nazzy- looking ic on and
appropriate profile, inc luding photos of his robot friends . I
s ugges t you do the s ame with your bot. P retty s oon it'll s tart
getting awes ome tes timonials , like the ones in Figure 5 - 1 3 (and
maybe even marriage propos als from other bots ! ).

Figure 5-13. Hipbot testimonials


See Also

[Hack #40]
Chapter 6. API Basics
H ac ks 3 7 - 4 2

T he A P I P age

A P I M ethods

A P I Keys and Sec rets

I dentifying U s ers

I dentifying G roups

I dentifying P hotos

D ec ons truc ting Flic kr U RL s

Talking to the A P I

H ac k 3 7 . Talk to the A P I with Your Web Brows er

H ac k 3 8 . Talk to the A P I with P erl

H ac k 3 9 . Talk to the A P I with P H P

H ac k 4 0 . A uthentic ate Yours elf

H ac k 4 1 . A uthentic ate U s ers

H ac k 4 2 . Build a C us tom U pload Sc ript


Hacks 37-42
T here's an obvious reas on why Flic kr has a larger and more
ac tive c ommunity of hac kers , tinkerers , and geeks than mos t
other photo- s haring s ervic es . I t's the inc redible applic ation
programming interfac e (A P I ), whic h lets you interac t with Flic kr
in unique and powerful ways . T he A P I makes it pos s ible to
perform H erc ulean tas ks that would otherwis e be impos s ible, or
at leas t extremely tedious , for a human. For example, C hapter 7
s hows how to us e the A P I to download thous ands of photographs
and build an elaborate and beautiful photo mos aic . I n this
c hapter, you'll learn the fundamentals of c ommunic ating with the
A P I , as well as the important kinds of information that the A P I
traffic s in.
The API Page
You c an learn to us e the Flic kr A P I without memorizing anything,
but there is one U RL you might want to c ommit to memory:

http://www.flic kr.c om/s ervic es /api/

T his is the loc ation of Flic kr's A P I doc umentation page (whic h
we'll refer to as "the A P I page" for s hort). T he A P I page
c ontains a lis t of eac h of the A P I methods , whic h are s ervic es
that Flic kr c an perform for you. E ac h method lis ted on the page
is linked to a des c ription of that partic ular method.

Some programmers , this one inc luded, ac c es s the A P I page


frequently enough that we c an type the U RL fas ter than we'd be
able to find the bookmark.
API Methods
T he Flic kr A P I methods are organized into groups by
func tionality. T his s ec tion provides a quic k overview of A P I as a
whole, but we rec ommend that you view the individual A P I
information pages on Flic kr for the partic ular c alls that pique
your interes t. A ls o, bear in mind that Flic kr's A P I is s till rapidly
growing and gaining in func tionality. C hec k the c urrent method
lis t at http://www.flic kr.c om/s ervic es /api/ to find new additions
and c hanges .

Authorization

T hes e methods are us ed to authenticate (i.e., authorize)


applic ations that us e the Flic kr A P I :

flickr.auth.checkToken
flickr.auth.getFrob
flickr.auth.getFullToken
flickr.auth.getToken

You might need to us e thes e methods if you intend to us e other


A P I methods that perform more invas ive tas ks , s uc h as deleting
photos or viewing your own private photos . H owever, we
rec ommend that, if pos s ible, you avoid us ing thes e methods by
making us e of one of the A P I kits that performs authentic ation
internally. phpFlickr (for P H P us ers ) and Flickr::API (for P erl
us ers ) are two exc ellent c hoic es . See [H ac k #4 0 ] and [Hack
#41] for examples .

Blogs
T hes e methods permit you to interac t with any blogs that you
have c onfigured to work with Flic kr:
flickr.blogs.getList
flickr.blogs.postPhoto

Contacts

T hes e methods permit you to produc e lis ts of your c ontac ts , or


s ome other us er's c ontac ts :
flickr.contacts.getList
flickr.contacts.getPublicList

Favorites

T hes e methods permit you to manipulate and view favorites


(photos that you or other people have marked for s pec ial
attention):
flickr.favorites.add
flickr.favorites.getList
flickr.favorites.getPublicList
flickr.favorites.remove

A t the time of this writing, it is not yet


eas y to determine with the A P I how many
people have marked a partic ular photo a
favorite, although this information is
dis played on the photo's detail page.
Groups

Groups , whic h are us ed both as dis c us s ion boards and as a


means for dis parate us ers to c ollec t and interac t with photos in
interes ting ways , are one of the great features of Flic kr. T he
following methods permit you to obtain group I D s and to produc e
lis ts of groups and of the photos in group photo pools :
flickr.groups.browse
flickr.groups.getInfo
flickr.groups.search
flickr.groups.pools.add
flickr.groups.pools.getContext
flickr.groups.pools.getGroups
flickr.groups.pools.getPhotos
flickr.groups.pools.remove

People

Flic kr is a s oc ial web s ite, s o it's important to be able to find out


more about the people us ing it. T hes e methods allow you to do
s o:
flickr.people.findByEmail
flickr.people.findByUsername
flickr.people.getInfo
flickr.people.getPublicGroups
flickr.people.getPublicPhotos
flickr.people.getUploadStatus

Some of the methods in this group, s uc h as


flickr.people.findByUsername, enable you to determine a us er's
I D number. You c an then pas s the us er's I D to other A P I c alls ,
s uc h as flickr.people.getInfo to find out more info about the
us er or flickr.people.getPublicPhotos to obtain a lis t of the
photos in that us er's s tream.

Photos

O f c ours e, photos are the bread, the butter, and the manna of
Flic kr, s o the majority of the A P I c alls are in the flickr.photos
group:
flickr.photos.addTags
flickr.photos.getAllContexts
flickr.photos.getContactsPhotos
flickr.photos.getContactsPublicPhotos
flickr.photos.getContext
flickr.photos.getCounts
flickr.photos.getExif
flickr.photos.getInfo
flickr.photos.getNotInSet
flickr.photos.getPerms
flickr.photos.getRecent
flickr.photos.getSizes
flickr.photos.getUntagged
flickr.photos.removeTag
flickr.photos.search
flickr.photos.setDates
flickr.photos.setMeta
flickr.photos.setPerms
flickr.photos.setTags
flickr.photos.transform.rotate
flickr.photos.upload.checkTickets

T he two c alls you're likely to us e mos t frequently are


flickr.photos.getInfo, whic h retrieves information about a
partic ular photo, and flickr.photos.search, whic h c an retrieve
lis ts of photos that matc h a partic ular tag, s et of tags , or other
c riteria.

Licenses
Flic kr s upports the C reative C ommons lic ens ing s ys tem [Hack
#16], and thes e c alls permit you to manipulate and query
lic ens e information:
flickr.photos.licenses.getInfo
flickr.photos.licenses.setLicense

M os t other c alls in the A P I that retrieve information about


photos , s uc h as flickr.photos.search and
flickr.groups.pool.getPhotos, will als o return lic ens e information
for photos .

Notes

You may have already notic ed that on Flic kr, you c an plac e notes
[Hack #10] direc tly on top of your photos , or other people's
photos . T hes e methods allow you to manipulate thos e notes :
flickr.photos.notes.add
flickr.photos.notes.delete
flickr.photos.notes.edit

U s e flickr.photos.getInfo to lis t the notes and tags for a


partic ular photo.

Photo Sets

T he photos in your s tream c an be organized into s ets , whic h are


c ollec tions of related photos (s uc h as all the photos you took on
your vac ation in Fres no). U s e thes e methods to manipulate and
ac c es s thos e s ets of photos :

flickr.photosets.addPhoto
flickr.photosets.create
flickr.photosets.delete
flickr.photosets.editMeta
flickr.photosets.editPhotos
flickr.photosets.getContext
flickr.photosets.getInfo
flickr.photosets.getList
flickr.photosets.getPhotos
flickr.photosets.orderSets
flickr.photosets.removePhoto

Reflection: API Information

T hes e methods return information about the A P I methods


thems elves , produc ing a c urrent lis t of the A P I methods and
des c ribing the information they provide:
flickr.reflection.getMethodInfo
flickr.reflection.getMethods

You c an als o get this s ame information (in more human- readable
form) by vis iting the A P I doc umentation page at
http://www.flic kr.c om/s ervic es /api/.

Tags

U s ers c an attac h tags [Hack #10] to photos on Flic kr, and thes e
A P I methods enable you to view thos e tags :
flickr.tags.getListPhoto
flickr.tags.getListUser
flickr.tags.getListUserPopular
flickr.tags.getRelated

You c an als o us e flickr.photos.getInfo to lis t the tags , as well as


c opious other information, for a partic ular photo.
Test

T hes e methods are intended for hac kers like us to tes t the A P I :

flickr.test.echo
flickr.test.login

You might find it jus t as eas y to us e s ome of the other A P I c alls ,


whic h is how we'll ac c omplis h the firs t tes ts in this c hapter.

URLs

O n Flic kr, you c an find us ers , photos , and groups at predic table
and fixed U RL s . I t's s imple enough to c ons truc t thes e U RL s out
of their c ons tituent parts by c onjoining s trings , but you c an als o
us e the firs t three methods in this group:

flickr.urls.getGroup
flickr.urls.getUserPhotos
flickr.urls.getUserProfile
flickr.urls.lookupGroup
flickr.urls.lookupUser

T he las t two methods c onvert U RL s to group I D s and us er I D s ,


res pec tively.

You'll find that mos t of the hac ks in this


book us e only a s mall s ubs et of the entire
c ollec tion of A P I methods . You c an
ac c omplis h an extraordinary amount with
jus t two A P I methods :
flickr.photos.search and
flickr.groups.pools.getPhotos.
API Keys and Secrets
A ll of the A P I methods have one required parameter, api_key,
whic h identifies your applic ation to Flic kr. Sinc e all the methods
require an A P I key, you s hould get one before you s tart
experimenting with the A P I .

To get an A P I key, s ign in to Flic kr and go to the following U RL


(whic h s hould look familiar by now):

http://www.flic kr.c om/s ervic es /api/

C lic k the A P I Keys link (under "Read thes e firs t:"), and then
c lic k the "A pply for your key online now" link. A lternatively, jus t
go direc tly to the following U RL , whic h is where you'll end up:

http://www.flic kr.c om/s ervic es /api/key.gne

Fill out the form, and pres s the A pply button. You'll be pres ented
with an A P I key, as s hown in Figure 6 - 1 . You c an rec ord this
information in a text file, or jus t return to the Flic kr A P I page
when you need to s ee it.

Figure 6-1. An API key


You need only one A P I key for
experimenting, but we rec ommend getting
a unique A P I key for eac h applic ation that
you intend to s hare with other people. T his
way, people c an as s ign different
permis s ions to eac h of your apps .

E ac h A P I key is is s ued with an ac c ompanying s hared s ecret, an


alphanumeric s tring that mus t be provided for the authentic ation
proc es s . You c an view the s hared s ec ret that goes with your A P I
key by vis iting the A P I page and c lic king the word "Yours " on
the line that s ays "A P I Keys (Yours )." For more info about
authentic ation, s ee [Hack #40] .
Identifying Users
M any of the A P I methods ac c ept a few parameters relating to
Flic kr us ers (like yours elf).

T he username is the name other us ers s ee next to your buddy


ic on, s uc h as when you pos t mes s ages in Flic kr groups . T hes e
are the names you s ee mos t c ommonly on Flic kr.

T he user_id is an alphanumeric s tring that uniquely identifies


eac h us er. I t c an be us ed in any U RL that refers to the us er, s uc h
as the us er's photos tream or profile page.

user_ids and group_ids are both ins tanc es


of N etwork Servic e I D s (N SI D s ): unique
s trings us ed to identify both us ers and
groups on Flic kr. A typic al N SI D is a s tring
of numbers , followed by an at s ign (@), an
N, and two more numbers (often 00 or 01).
H ere's a typic al N SI D : 94832693@N00. I f
you learn to rec ognize this pattern, it'll be
eas ier to pic k it out of U RL s .

Flic kr is now beginning to integrate its


s ervic es into Yahoo! , s o the user_id and
group_id s trings might eventually deviate
from the N SI D format. Bec aus e of this ,
mos t A P I c alls that return I D s provide
both an I D and an N SI D . A t time of this
writing, thes e two fields are always
identic al, but you s hould be c areful to us e
one or the other c ons is tently to avoid
future problems with your s c ripts .

A n eas y way to dis c over your own user_id without us ing the A P I
is to view the image properties of your Flic kr ic on and examine
the U RL of the image. M y ic on's U RL reads as follows (my
user_id is s hown in bold):

http://photos2.flickr.com/buddyicons/94832693@N00.jpg?1119657139

T he link to your RSS feed on your photos tream page als o


c ontains your user_id.

Finally, the alias is a name you c an c hoos e to give your Flic kr


page a permanent, more readable U RL , in addition to the U RL
that c ontains the user_id. T his alias is not nec es s arily the s ame
as your us ername, and unlike your us ername, onc e you c reate
the alias you c annot c hange it. P eople s ometimes s tart with
alias es that are the s ame as their us ernames but then c hange
their us ernames . For example, on Flic kr, my us ername is j bum,
but my alias is krazydad, s o my photos c an be found here:

http://www.flic kr.c om/photos /krazydad/

I t's eas ier for other people to gues s your Flic kr web addres s if
you make your alias the s ame as your us ername. I probably
s hould have c hos en j bum for my alias , but now it's too late. O h
well!

N ot every us er has an alias . You c an tell if the us er does by


vis iting her photo page. I f the U RL s till c ontains an N SI D , it
means the us er has not pic ked out an alias yet. H owever, even
after the us er pic ks out an alias , the N SI D will s till work for
c ons truc ting U RL s to the us er's pages . T hus , you c an als o reac h
my photos by us ing this U RL :

http://www.flic kr.c om/photos /9 4 8 3 2 6 9 3 @ N 0 0 /

T here are far more c alls in the A P I that provide us er I D s than


alias es , s o it's us ually eas ier for programs to c ons truc t U RL s
us ing I D s .
Identifying Groups
T he group_id is an N SI D that uniquely identifies a group and c an
be us ed in any U RL that refers to the group.

T he poolname is to a group what the alias is to a us er. A poolname


provides a permanent, readable web addres s for the group. O nc e
as s igned, a poolname c annot be c hanged. L ike an alias , the
poolname does not nec es s arily c orres pond to the group's name
as it appears in the group lis ting. For example, the poolname of
the Squared C irc le group is jus t circle, as illus trated in the
group's U RL :

http://www.flic kr.c om/groups /c irc le/

A gain, it's eas ies t for us ers if the poolname c orres ponds to the
group name, but in ac tuality this does n't happen that often,
s inc e there are often multiple groups that deal with the s ame
kinds of s ubjec ts . I f you want to c reate a group for c ollec ting
pic tures of mus hrooms , c hanc es are you're not the firs t!
M us hrooms , Fungi, and Fungus are already taken. A t the
moment, M yc ology is s till free. G rab it while you c an!
Identifying Photos
J us t about every A P I method that returns information about
photos returns the following three piec es of information:

photo_id

A dec imal number that identifies a photo. E ac h photo


gets a unique number, and the numbers have been ris ing
s inc e Flic kr has been in exis tenc e. L ike rings on a tree
trunk, you c an c ome up with a rough gues s of when a
photo was uploaded to Flic kr by looking at how low its I D
number is .

secret

A n alphanumeric s tring that is required to form a valid


U RL to a photo's image file.

server

A number that, like the secret, is required to form a valid


U RL to a photo's image file. A t one time, thes e numbers
c orres ponded to individual L udic orp s ervers , although
that might now be a pleas ant fic tion. N onetheles s , the
number is s till nec es s ary.

While the photo_id is often dis played public ly in the brows er's
addres s bar (as part of the U RL for the photo's detail page), the
secret and server are normally not vis ible to end us ers , making it
s lightly harder for c as ual brows ers to s wipe photos from Flic kr.
Fortunately for us , there's an eas y way to retrieve this info
without even us ing the A P I .

I f you're on a photo's detail page, you c an get the goods by


invoking the photo's image properties and examining the U RL .
For example, I have a photo with the following U RL :

http://www.flic kr.c om/photos /krazydad/1 6 8 0 4 2 0 5 /

From this , we c an s ee that the photo's I D is 16804205 and my


alias is krazydad.

To ac c es s the image properties , right- c lic k (C ontrol- c lic k on a


M ac ) the photo. You'll s ee the following U RL to the photo's J P E G
file:

http://s tatic .flic kr.c om/1 3 /1 6 8 0 4 2 0 5 _8 1 4 6 5 3 c 7 8 b.jpg?


v=0

I gnoring the s hmutz after the ques tion mark, the U RL is


c ons truc ted thus ly:

http://static.flickr.com/server/id_secret.jpg

T his tells us that the photo's secret is 16804205 and its server is
13.
Deconstructing Flickr URLs
You may have notic ed in the previous s ec tion that Flic kr us es
c ons is tent naming c onventions for its U RL s . T his makes it eas y
to c ons truc t thes e U RL s , given c ruc ial bits of information s uc h
as user_ids and photo_ids . H ere are s ome examples :

U RL s for photos treams :

http://www.flickr.com/photos/<user_id>
http://www.flickr.com/photos/<alias>

U RL s for profiles :

http://www.flickr.com/people/<user_id>
http://www.flickr.com/people/<alias>

U RL s for groups :

http://www.flickr.com/groups/<group_id>/
http://www.flickr.com/gouprs/<poolname>/

U RL S for photo pages :

http://www.flickr.com/photos/<user_id>/<photo_id>/
http://www.flickr.com/photos/<alias>/<photo_id>/
http://flickr.com/photo.gne?id=<photo_id>

U RL S for photo image files :

http://static.flickr.com/<server>/<photo_id>_<secret>.jpg
http://static.flickr.com/<server>/<photo_id>_<secret>_<size>.jpg

N ote that the unders c ores between


<photo_id> and <secret> and between
<secret> and <size> in the prec eding U RL s
are required. T he unders c ores thems elves
are not part of the replac eable values .
I f the <size> qualifier is left out, you'll get the medium- s ized
vers ion of the image, whic h is 5 0 0 pixels on the longes t s ide.
For a lis t of <size> options , s ee [Hack #34] .
Talking to the API
You c ommunic ate with the Flic kr A P I by s ending it reques ts via
the H T T P protoc ol and then pars ing the res ults , whic h are
returned as XM L .

T he s imples t way to talk to the A P I is by typing thes e reques ts


in your brows er's addres s bar [Hack #37] . H owever, you will
us ually talk to it with a programming language, s uc h as P erl
[H ac k #3 8 ] or P H P [Hack #39] .

T he Flic kr A P I c urrently s upports three different


reques t/res pons e protoc ols (or formats ), c orres ponding to
c urrently popular s tandards for c ommunic ating with s ervic es on
the I nternet. I n eac h format the underlying data being
c ommunic ated is the s ame, but the XM L data is gift- wrapped in a
different way:

REST

RE ST is a rapidly growing informal "s tandard" that is the


s imples t (by far! ) of the three protoc ols lis ted here. T his
s implic ity is the reas on for its popularity. Reques ts are
made by is s uing s imple H T T P GET or POST ac tions , and
res pons es are returned via XM L with few additional
trappings .

XML-RPC

XM L- RP C reques ts are s pec ially formatted XM L data


pos ted to a U RL . You c an find out more about XM L- RP C
at http://www.xmlrpc .c om.

SOAP

SO A P is another popular s tandard protoc ol for


c ommunic ating via XM L . You c an find out more about
SO A P at http://www.w3 .org/T R/s oap/.

I f trying to pic k one of thes e protoc ols is


wearing you out, might we s ugges t taking a
RE ST ? RE ST is the protoc ol that the
majority of Flic kr developers ac tually us e,
bec aus e it c arries the leas t baggage and
requires the s malles t amount of overhead
to pars e the res ults . I t is the only protoc ol
that you c an eas ily experiment with by
typing reques ts in your web brows er's
addres s bar. T he mos t c ompelling reas on
for us ing XM L- RP C or SO A P is if you are
integrating Flic kr into an app that already
us es one of thes e more c omplex formats .
M os t of the A P I examples in this book us e
the RE ST protoc ol.

So, now that you've gotten a glimps e of the different piec es of


the A P I , let's s tart playing with it, s hall we?
Hack 37. Talk to the API with Your Web
Browser

Making requests with your web browser is a great way to


f amiliarize yourself with the Flickr A PI.

Before us ing a programming language (s uc h as P erl [H ac k #3 8 ]


or P H P [Hack #39] ) to talk to the Flic kr A P I , it's a good idea to
tes t it us ing your web brows er. I f you are us ing a new A P I
method, this is an exc ellent way to get us ed to it and to view the
XM L that is returned by the c all. I f you are unfamiliar with the
mec hanic s of RE ST and XM L , it is als o a good way to explore
how thes e protoc ols work.

T here are two s imple ways to talk to the A P I us ing your web
brows er: you c an type RE ST U RL s direc tly into your brows er's
addres s bar (the hard way), or you c an us e Flic kr's A P I E xplorer
(the eas y way).

Using REST URLs

T he firs t method, us ing your brows er's addres s bar, is mainly of


his toric al interes t, bec aus e the s ec ond method is s o muc h
eas ier. But let's s ee how it works , for c ompletenes s 's s ake.

You c an us e any Flic kr A P I method, s uc h as flickr.test.echo, by


entering its name and any required parameters into your
brows er's addres s bar in the Flic kr RE ST format.

H ere's an example. Try pas ting this into your web brows er's
addres s bar:

http://www.flickr.com/services/rest/?method=flickr.test.echo&api_k

Subs titute your own A P I key for your_api_key, and s ubs titute the
name of any Flic kr A P I method for flickr.test.echo. You c an als o
add any parameters that are required by the c all, jus t as the
above example us es param1 and param2 with flickr.test.echo.

I f you us e a valid A P I key, you'll get a res ult like this :

<rsp stat="ok">
<method>flickr.test.echo</method>
<api_key>81a8f5d6c402d26f425e4361d07f85ba</api_key>
<foo>bar</foo>
</rsp>

T he main problem with typing A P I U RL s direc tly is that you need


a valid A P I key, and you might not have one handy.

You c an apply for an A P I key at


http://www.flic kr.c om/s ervic es /api/key.gne.
A ls o, it is often diffic ult to determine c orrec t values for the
various parameters you might want to us e without is s uing other
A P I methods , whic h c reates a kind of c hic ken- and- egg problem
when you want to tes t the A P I .

To s olve this problem, the Flic kr folks have c ome up with an


exc ellent tool c alled the API Explorer, the "eas y way" mentioned
earlier and dis c us s ed in the following s ec tion.

Using the API Explorer

T he A P I E xplorer generates a temporary Flic kr A P I key and


gives you the option of s igning eac h c all with full permis s ions . I t
als o produc es a lis t of helpful values , s uc h as photo I D s , group
I D s , and s o on, whic h are quite us eful for generating example
res ults .

To us e the A P I E xplorer, vis it the doc umentation page for the


partic ular method you are interes ted in. You'll find a link to the
A P I E xplorer at the bottom of the page. T he table of c ontents for
all of the A P I methods is loc ated at an addres s that's well worth
bookmarking:

http://www.flic kr.c om/s ervic es /api/

From there, you c an find the A P I E xplorer for eac h method pretty
quic kly.

T he next few hac ks us e flickr.photos.getInfo as an example.


T his is the A P I c all that retrieves detailed information about a
partic ular photo. T he doc umentation page for
flickr.photos.getInfo is loc ated at
http://www.flic kr.c om/s ervic es /api/flic kr.photos .getI nfo.html.

C lic king the A P I E xplorer link at the bottom of this page will
take you to the A P I E xplorer form s hown in Figure 6 - 2 , whic h
res ides at http://www.flic kr.c om/s ervic es /api/explore/?
method=flic kr.photos .getI nfo.

Figure 6-2. Flickr API Explorer for


flickr.photos.getInfo
You'll notic e that there is a required parameter for this c all,
whic h is the photo_id of the photo we're interes ted in learning
about. Sinc e we're tes ting the method and don't partic ularly c are
about whic h photo we're getting info on, we c an us e one of the
photo I D s s hown in the U s eful Values c olumn on the right. A few
values s hould be lis ted under "Your rec ent photo I D s ."

C opying and pas ting the I D of the photo labeled "A ll the c at toys
on A mazon" (60147370) and then pres s ing the C all M ethod...
button produc es the following XM L :

<rsp stat="ok">
<photo id="60147370" secret="0bdfee3691" server="30" dateuploaded=
<owner nsid="94832693@N00" username="jbum" realname="Jim Bumgardne
<title>All the cat toys on Amazon</title>
<description>
All the cat toys on Amazon.

Interactive version here:

<a href="http://www.coverpop.com/pop/cattoys/">http://www.coverpop

</description>
<visibility ispublic="1" isfriend="0" isfamily="0"/>
<dates posted="1131226468" taken="2005-11-05 13:34:28" takengranul
<permissions permcomment="3" permaddmeta="2"/>
<editability cancomment="1" canaddmeta="1"/>
<comments>1</comments>
<notes>
</notes>
<tags>
<tag id="197715539" author="94832693@N00" raw="cats">cats</tag>
<tag id="197715540" author="94832693@N00" raw="cat toys">cattoys</
<tag id="197715541" author="94832693@N00" raw="amazon">amazon</tag
<tag id="197715542" author="94832693@N00" raw="mosaic">mosaic</tag
<tag id="197715543" author="94832693@N00" raw="coverpop">coverpop<
</tags>
<urls>
<url type="photopage">http://www.flickr.com/photos/krazydad/601473
</urls>
</photo>
</rsp>

I t's als o ins truc tive to enter invalid information and s ee what
kind of res ult you get. For example, entering aaaa for the photo_id
(whic h is not a valid photo_id) returns the following res ult:

<rsp stat="fail">
<err code="1" msg="Photo not found"/>
</rsp>

T he XM L res ults from all the Flic kr A P I methods exhibit this


s ame rudimentary s truc ture. T here is an <rsp> tag c ontainer,
whic h has either an ok or fail s tat property. I f the c all is a
failure, there will als o be an <err> tag, whic h c ontains a helpful
error mes s age in the msg property. I f the c all s uc c eeds , the <rsp>
c ontainer will c ontain the res ult of the c all, whic h varies from
A P I method to A P I method.

I n the next c ouple of hac ks , we'll s ee how to us e


flickr.photos.getInfo, as well as s ome other A P I methods , with
P erl [Hack #38] and P H P [Hack #39] . We'll als o s ee different
ways to pars e the XM L and make us e of it. Before proc eeding,
get yours elf a Flic kr A P I key by vis iting
http://www.flic kr.c om/s ervic es /api/key.gne. You're going to need
it very s oon!

See Also
[Hack #38]

[Hack #39]
Hack 38. Talk to the API with Perl

Perl is a good choice f or talking to the A PI f rom the command


line.

T his hac k pres ents a few different P erl s c ripts that talk to the
Flic kr A P I . Firs t, s ome s imple examples s how the bas ic method;
the two different tec hniques that follow it ac c omplis h a more
us eful tas k. T he programs in [Hack #39] mirror the programs in
this hac k.

What You Need

Talking to the Flic kr A P I requires you to s olve two fundamental


problems . T he firs t problem is how to is s ue a c all to the A P I . To
do this , this hac k us es two different modules . T he firs t few
programs us e the c ommonly available LWP::Simple module, and
the final program us es Flickr::API, whic h is a higher- level
module built on top of the LWP::Simple module.

T he s ec ond problem you need to s olve is how to interpret the


res ult you get bac ks pec ific ally, how to pars e the XM L . I n the
P erl c ommunity, a bewildering number of XM L pars ers are
available. Flickr::API ac tually does s ome XM L pars ing for you,
but I don't partic ularly like the XM L pars er it us es , s o this
c hapter us es XML::Simple, whic h produc es a s impler and more
elegant data s truc ture than s ome of the other XM L pars ers .
Regardles s of whic h XM L pars er you us e, it is muc h eas ier to
figure out how to us e it if you examine the data s truc tures it
produc es us ing the Data::Dumper module.

So, to s um up, we're going to us e thes e four P erl modules :


LWP::Simple
Flickr::API
XML::Simple
Data::Dumper

You c an download all of thes e modules from C P A N . O n L inux and


M ac s ys tems , you c an ins tall the modules on the c ommand line
us ing P erl. For example, here's how to ins tall Flickr::API:

> perl -MCPAN -e shell


cpan> install Flickr::API

I n Windows , partic ularly with A c tiveState P erl, it is eas ier to us e


the ppm utility. For example:

> ppm install Flickr::API

L et's s tart with a program that does the bare minimum.

Getting a User's ID

T he firs t program us es LWP::Simple to talk to the A P I , c onverting


a us ername into a Flic kr us er I D . Sinc e mos t of the Flic kr A P I
c alls that return information about us ers require a user_id as a
parameter, this is a us eful c all to mas ter. C reate a new text file
c alled tes tapi.pl and enter the following c ode:

#!/usr/bin/perl -s

use LWP::Simple;

$username = shift;
die ("Please specify a Flickr username\n") if !$username;

$api_key = 'your_api_key'; # insert your API key here


$method = 'flickr.people.findByUsername';

$url = "http://www.flickr.com/services/rest/?method=$method&api_ke
$xml = get $url;

print $xml;

You'll need to c hange the following line:

$api_key = 'your_api_key'; # insert your API key here

s o that it inc ludes your own A P I key, like this :

$api_key = 'e072dadf32c2a6da1b7b7592e88ebe9e';
You c an apply for an A P I key at
http://www.flic kr.c om/s ervic es /api/key.gne.

A s you c an s ee, this program bas ic ally c ons truc ts a RE ST U RL


that is the s ame as the U RL s you c an type direc tly into your web
brows er's addres s bar [Hack #37] . I t retrieves the res ult us ing
the get() func tion, whic h is provided by LWP::Simple, and then
dis plays the res ult as text.

H ere's a s ample run:

> testapi.pl jbum


<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<user id="94832693@N00" nsid="94832693@N00">
<username>jbum</username>
</user>
</rsp>

I f all you want to do is find out a us er I D , this might be all you


need. H owever, it would be nic e to dis play it in a more readable
fas hion. You c an extrac t the us er I D us ing P erl's pattern
matc hing:

($id) = $xml =~ m/nsid="(.*)"/;


print "User ID: $id\n";
But there's a more flexible way, whic h is to us e an XM L pars er.
T his might s eem a bit c omplic ated now, but it will make pars ing
more c omplex XM L eas ier. H ere's a rewrite of the program us ing
the XML::Simple pars er and the Data::Dumper module:

#!/usr/bin/perl -s

use LWP::Simple;
use XML::Simple;
use Data::Dumper;

$username = shift;
die ("Please specify a Flickr username\n") if !$username;

$api_key = 'your_api_key'; # insert your API key here


$method = 'flickr.people.findByUsername';

$method = 'flickr.people.findByUsername';
$url = "http://www.flickr.com/services/rest/?method=$method&api_ke
$xml = get $url;
$xm = XMLin($xml);

print Dumper($xm),"\n" if $debug;

if ($xm->{err})
{
print "Error getting user id: ",$xm->{err}->{msg},"\n";
exit;
}
$user_id = $xm->{user}->{id};
print "User ID: $user_id\n";
T his program takes an optional option, -debug, whic h c an be us ed
to dump the c ontents of the data s truc ture produc ed by XMLin(),
the pars ing func tion provided by XML::Simple. T he program dumps
it us ing the Dumper() func tion provided by Data::Dumper, an
inc redibly helpful way to figure out what kind of data s truc tures
you are being c onfronted with. H ere's a s ample run with
debugging turned on:

> testapi2.pl -debug jbum


$VAR1 = {
'user' => {
'nsid' => '94832693@N00',
'id' => '94832693@N00',
'username' => 'jbum'
},
'stat' => 'ok'
};

User ID: 94832693@N00

You might have notic ed that the nsid and id fields in the returned
data s truc tures are the s ame. A t the moment, Flic kr I D s and
N SI D s are identic al, and we'll tend to us e them interc hangeably
in this book. I t is pos s ible, though, that at s ome time in the
future the two I D s ys tems will diverge.

T he $VAR1 = at the beginning of the Dumper()


output is meaningles s . VAR1 is a
plac eholder for the variable you are
dumping. I prefer to omit it by s etting
Data::Dumper to ters e mode. You c an
ac c omplis h this by adding this line near
the top of the program:

$Data::Dumper::Terse = 1; # avoids $VAR1 = * ;


# in dumper output

You'll s ee this in us e in the next example.

Viewing a User's Latest Photo

T he next program us es the s ame bas ic tec hniques but


introduc es two new A P I c alls . T he program takes a us ername,
c onverts it into a user_id, and then us es that user_id to look up
the mos t rec ent photo in the us er's s tream, us ing
flickr.people.getPublicPhotos. I t then gets a little more info
about the photo us ing flickr.photos.getInfo and generates an
H T M L page that c ontains a view of the photo and the information
that was retrieved.

C reate a new file c alled getUs ers Lates t.pl and add the following
P erl c ode:

#!/usr/bin/perl -s

use LWP::Simple;
use XML::Simple;
use Data::Dumper;
$Data::Dumper::Terse = 1; # avoids $VAR1 = * ; in dumper output

$api_key = 'your_api_key'; # insert your Flickr API key here

$username = shift;
die ("Please specify a Flickr username\n") if !$username;

#
# Get user's ID
#
$method = 'flickr.people.findByUsername';
$url = "http://www.flickr.com/services/rest/?method=$method" .
"&api_key=${api_key}&username=${username}";
$xml = get $url;
$xm = XMLin($xml);

print Dumper($xm),"\n" if $debug;

if ($xm->{err})
{
print "Error getting user id: ",$xm->{err}->{msg},"\n";
exit;
}
$user_id = $xm->{user}->{id};
#
# Get user's most recent photos
#

$method = 'flickr.people.getPublicPhotos';
$url = "http://www.flickr.com/services/rest/?method=$method" .
"&api_key=$api_key&user_id=$user_id&per_page=1";
$xml = get $url;
$xm = XMLin($xml);
print Dumper($xm),"\n" if $debug;

if ($xm->{err})
{
print "Error getting most recent photo: ",$xm->{err}->{msg},"\
exit;
}
$photo_id = $xm->{photos}->{photo}->{id};
$photo_secret = $xm->{photos}->{photo}->{secret};
$photo_server = $xm->{photos}->{photo}->{server};

#
# Formulate URL to the photo (image)
#
$imgUrl = sprintf "http://static.flickr.com/%d/%d_%s.jpg",
$photo_server,$photo_id, $photo_secret;

#
# Formulate URL to the photo's Flickr page
#
$pageUrl = sprintf "http://www.flickr.com/photos/%s/%d/",
$user_id, $photo_id;
#
# Get photo info
#
$method = 'flickr.photos.getInfo';
$url = "http://www.flickr.com/services/rest/?method=$method" .
"&api_key=$api_key&photo_id=$photo_id";
$xml = get $url;
$xm = XMLin($xml);
print Dumper($xm),"\n" if $debug;

if ($xm->{err})
{
print "Error getting most recent photo: ",$xm->{err}->{msg},"\
exit;
}

#
# Get title
#
$title = $xm->{photo}->{title};

#
# Get date uploaded
#
$dateuploaded = $xm->{photo}->{dateuploaded};
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(
$datestr = sprintf '%4d-%02d-%02d %2d:%02d', $year+1900,$mon+1,$md

#
# Join tags into a single string
#
$tags = $xm->{photo}->{tags}->{tag};
$taglist = join ', ',map {$tags->{$_}->{content}} keys %{$tags};
#
# Output HTML page containing URL to photo, image, and tags.
#
print <<EOT;
<html>
<head>
<title>Sample Photo Page</title>
</head>
<body>
<center>
The latest from $username...<br>
<a href="$pageUrl"><img src="$imgUrl" /></a><br>
Title: $title<br>
Uploaded: $datestr<br>
$taglist
</center>
</body>
</html>
EOT

T he final s ec tion of this program outputs s ome H T M L to


s tandard output. To us e the program, redirec t it into an H T M L
file, and then view the H T M L file in your web brows er.

H ere's a s ample, run, s howing the H T M L :

> getUsersLatest.pl jbum


<html>
<head>
<title>Sample Photo Page</title>
</head>
<body>
<center>
The latest from jbum...<br>
<a href="http://www.flickr.com/photos/94832693@N00/61321455/"><img
tatic.flickr.com/25/61321455_eee1263b27.jpg" /></a><br>
Title: The visitor<br>
Uploaded: 2005-11-08 10:47<br>
alien, coverpop, mosaic, ufo, visitor, paranormal
</center>
</body>
</html>

Figure 6 - 3 s hows the res ult as it looks in my web brows er.

Figure 6-3. Viewing a user's latest photo


T he H T M L c ode here that dis plays the
photo embeds it within a link bac k to the
Flic kr page for that partic ular photo. T he
Flic kr Terms of Servic e reques t that you
always provide a link bac k to Flic kr with
eac h photo you dis play, and this is a
c ommon way of doing it.

Some of the data s truc tures involved here are bit c omplic ated,
and it is not eas y to predic t how to generate the c omplex
referenc es needed to extrac t c ertain fields , as in this line:

$photo_id = $xm->{photos}->{photo}->{id};

I n eac h c as e, I firs t implemented the Dumper() part of the


program and ran it, s o I c ould view the data s truc ture that I
needed to travers e. Regardles s of whic h XM L pars er you c hoos e
to us e, this is a helpful tec hnique for figuring out what you're
dealing with. I 've left the data- dumping feature in this program,
to be triggered by the -debug option.

Viewing a User's Latest Photo Using


Flickr::API

T his next program is a port of the previous one with exac tly the
s ame features . T he only differenc e is that it us es Flickr::API
ins tead of LWP::Simple. Flickr::API is intended to provide a layer
of glue, freeing you from the nitty- gritty details of dealing with
the A P I . I n this c as e, however, you'll notic e that both programs
are nearly the s ame length!

C reate a new file c alled getUs ers Lates t2.pl and add the following
P erl c ode:

#!/usr/bin/perl -s

use Flickr::API; # replaces use of LWP::Simple


use XML::Simple;
use Data::Dumper;
$Data::Dumper::Terse = 1; # avoids $VAR1 = * ; in dumper output

$api_key = 'your_api_key'; # insert your Flickr API key here


$username = shift;
die ("Please specify a Flickr username\n") if !$username;

#
# Initialize Flickr API
#
my $api = new Flickr::API({'key' => $api_key});

#
# Get user's ID
#

my $response = $api->execute_method('flickr.people.findByUsername'
username => $username}
);
if (!$response->{success})
{
print "Error getting user id: ",$response->{error_message},"\n
exit;
}
$xm = XMLin($response->{_content});
print Dumper($xm),"\n" if $debug;

$user_id = $xm->{user}->{id};

#
# Get user's most recent photos
#

my $response = $api->execute_method('flickr.people.getPublicPhotos
user_id => $user_id,
per_page => 1}
);

if (!$response->{success})
{
print "Error getting most recent photo: ",$response->{error_me
exit;
}
$xm = XMLin($response->{_content});
print Dumper($xm),"\n" if $debug;

$photo_id = $xm->{photos}->{photo}->{id};
$photo_secret = $xm->{photos}->{photo}->{secret};
$photo_server = $xm->{photos}->{photo}->{server};

#
# Formulate URL to the photo (image)
#
$imgUrl = sprintf "http://static.flickr.com/%d/%d_%s.jpg",
$photo_server,$photo_id, $phot

#
# Formulate URL to the photo's Flickr page
#
$pageUrl = sprintf "http://www.flickr.com/photos/%s/%d/",
$user_id, $photo_id;

#
# Get photo info
#
my $response = $api->execute_method('flickr.photos.getInfo', {
photo_id => $photo_id}
);
if (!$response->{success})
{
print "Error getting photo info: ",$response->{error_message},
exit;
}
$xm = XMLin($response->{_content});
print Dumper($xm),"\n" if $debug;

#
# Get title
#
$title = $xm->{photo}->{title};

#
# Get date uploaded
#
$dateuploaded = $xm->{photo}->{dateuploaded};
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(
$datestr = sprintf '%4d-%02d-%02d %2d:%02d', $year+1900,$mon+1,$md

#
# Join tags into a single string
#
$tags = $xm->{photo}->{tags}->{tag};
$taglist = join ', ',map {$tags->{$_}->{content}} keys %{$tags};

#
# Output HTML page containing URL to photo, image, and tags.
#
print <<EOT;
<html>
<head>
<title>Sample Photo Page</title>
</head>
<body>
<center>
The latest from $username...<br>
<a href="$pageUrl"><img src="$imgUrl" /></a><br>
Title: $title<br>
Uploaded: $datestr<br>
$taglist
</center>
</body>
</html>
EOT

I f you look c los ely, you'll s ee that the two programs are nearly
identic al and that in this c as e, Flickr::API is n't really buying you
very muc h. A n additional line has been added near the top to
initialize Flickr::API:
my $api = new Flickr::API({'key' => $api_key});

T he c alls to get() have been replac ed by c alls to api-


>execute_method(), and the res ults are proc es s ed s lightly
differently. T his program could be made s lightly s horter, by taking
advantage of the XM L pars ing that Flickr::API does . For
example, to read the firs t photo's I D , ins tead of s aying this :

$xm = XMLin($response->{_content});
$photo_id = $xm->{photos}->{photo}->{id};

you c ould omit the XMLin() s tep and s ay this , in jus t one line:

$photo_id = $response->{tree}->{children}->[1]->{children}->[1]->{

H owever, you'll notic e that the data s truc ture that mus t be
travers ed to find the photo I D (a data s truc ture produc ed by
XML::Parser::Lite::Tree, the XM L pars er us ed internally by
Flickr::API) is more intric ate (and, to my eye, les s intuitive
bec aus e of all thos e generic - looking children) than the s truc ture
returned by XML::Simple. T his intric ac y generally leads to more
c oding mis takes , s o I prefer to us e XML::Simple.

So, why us e Flickr::API at all? A s you'll s ee in [Hack #40], it is


enormous ly helpful for A P I c alls that require authentic ation, one
of the more c omplic ated bits of the Flic kr A P I .
See Also

[Hack #37]

[Hack #39]

[Hack #40]
Hack 39. Talk to the API with PHP

PHP is a good choice f or creating web-based Flickr tools.

H aving looked at how to talk to the A P I in P erl [Hack #38], this


hac k ac c omplis hes the s ame tas ks in P H P. A gain, we'll s tart
with a s imple example and then move on to a more c omplic ated
tas k us ing the two available A P I kits : PEAR::Flickr_API and
phpFlickr. A c c omplis hing the s ame tas k in eac h kit will enable
you to c ontras t and c ompare them.

What You Need

Sinc e we're programming in P H P, you'll need a web s erver with


P H P ins talled. A ll the programs in this hac k require P H P 4 or
later.

Some of the XM L pars ing c an be made


muc h s impler if you have ac c es s to P H P 5
and the SimpleXML extens ions , but s inc e
many folks are forc ed to live with P H P 4 ,
we'll keep thes e programs c ompatible with
the earlier vers ion.
We'll be us ing the two c urrently available A P I kits for talking to
Flic kr from P H P : PEAR::Flickr_API (available at
http://c ode.iamc al.c om/php/flic kr/) and phpFlickr (available at
http://www.phpflic kr.c om).

A ny new A P I kits that bec ome available


after the public ation of this book will be
lis ted at the Flic kr A P I page
(http://www.flic kr.c om/s ervic es /api/).

Talking to the Flic kr A P I in any language requires that you s olve


two fundamental problems . T he firs t problem is how to is s ue a
c all to the A P I . T he s ec ond is how to pars e the XM L you get
bac k. I n P H P 4 , s olving the firs t problem is quite s imple, but
pic king your way through the tangly XM L thic ket c an be a
c hallenge.

We'll s tart with a program that does the bare minimum.

Getting a User's ID

T his firs t program talks to the A P I without us ing an A P I kit.

C reate a new text file c alled tes tapi.php and enter the following
c ode:

<?

$api_key = 'your_api_key'; # Insert your Flickr API key here

$username = 'jbum';
if (isset($_GET['username']))
$username = $_GET['username'];

#
# Get user's ID
#
$method = 'flickr.people.findByUsername';
$url = "http://www.flickr.com/services/rest/?method=$method&api_ke
$response = file_get_contents($url);

echo htmlspecialchars($response);
?>

You'll need to c hange the following line:

$api_key = 'your_api_key'; # Insert your Flickr API key here

s o that it inc ludes your own A P I key, like this :

$api_key = 'e072dadf32c2a6da1b7b7592e88ebe9e';
You c an apply for an A P I key at
http://www.flic kr.c om/s ervic es /api/key.gne.

A s you c an s ee, this program is c ons truc ting a RE ST U RL that is


the s ame as the U RL s you c an type direc tly into your web
brows er's addres s bar [Hack #37] . I t retrieves the res ult us ing
the file_get_contents() func tion and then dis plays the res ult as
text. Sinc e the res ult is XM L and c ontains tags , the
htmlspecialchars func tion is us ed to get it to dis play properly in
your brows er.

To tes t the program (and all the programs in this hac k), upload it
to your web s erver and then type the addres s of the program into
your brows er's addres s bar:

http://www.yourdomain.com/testapi.php

You c an tes t it with a us ername other than j bum (s ay, Special) by


adding it as an optional parameter:

http://www.yourdomain.com/ testapi.php?username=special

H ere's an example of the XM L produc ed by a s ample run:


<?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok"> <user id="

A s you c an s ee, invoking the A P I is relatively s imple. T he hard


part is extrac ting the data you need out of the XM L .

Sinc e the A P I kits available for P H P inc lude XM L pars ing, this is
a good time to s tart us ing them. We'll s tart with the firs t A P I kit
that was made for P H P.

Getting a User's ID Using


PEAR::Flickr_API

H ere is a modific ation of the previous program, us ing


PEAR::Flickr_API:

<?

require_once 'Flickr/API.php';

$api_key = 'your_api_key'; # Insert your Flickr API key here

$api =&new Flickr_API(array('api_key' => $api_key));

$username = 'jbum';
if (isset($_GET['username']))
$username = $_GET['username'];

#
# Get user's ID
#
$response = $api->callMethod('flickr.people.findByUsername',
array(

if (!$response)
{
echo "Error getting user id: ".$api->getErrorMessage( )."\n";
exit;
}

$user = $response->getElement(array(0));
$user_id = $user->getAttribute('id');

print "User_ID: $user_id<p>";

?>

To us e this program, you'll need to again replac e $api_key with an


ac tual A P I key. You'll als o need to have already ins talled
PEAR::Flickr_API. A s imple way to ins tall it is to c opy the four
direc tories in its arc hive (Flickr, HTTP, Net, and XML) into the
s ame direc tory where your P H P s c ripts res ide.

Viewing a User's Latest Photo with


PEAR::Flickr_API

T he next program expands upon the previous program and


introduc es two new A P I c alls . T he program takes a us ername,
c onverts it into a user_id, and then us es that user_id to look up
the mos t rec ent photo in the us er's s tream, us ing
flickr.people.getPublicPhotos. I t then gets a little more info
about the photo us ing flickr.photos.getInfo and generates an
H T M L page that c ontains a view of the photo and the information
that was retrieved.

C reate a new file c alled getUs ers Lates t.php and add the following
c ode:

<?

require_once 'Flickr/API.php';

$api_key = 'your_api_key'; # insert your actual API key

$api =&new Flickr_API(array('api_key' => $api_key));

$username = 'jbum';
if (isset($_GET['username']))
$username = $_GET['username'];

#
# Get user's ID
#
$response = $api->callMethod('flickr.people.findByUsername',
array( 'username' => $username ));

if (!$response)
{
echo "Error getting user id: ".$api->getErrorMessage( )."\n";
exit;
}

$nom = $response->getElement(array(0));
$user_id = $nom->getAttribute('id');
#
# Get user's most recent photos
#

$response = $api->callMethod('flickr.people.getPublicPhotos', arra


'user_id' => $user_id,
'per_page' => 1 ));

if (!$response)
{
print "Error getting most recent photo: ".$api->getErrorMessag
exit;
}
$photo = $response->getElement(array(0,0));
$photo_id = $photo->getAttribute('id');
$photo_secret = $photo->getAttribute('secret');
$photo_server = $photo->getAttribute('server');

#
# Formulate URL to the photo (image)
#
$imgUrl = "http://static.flickr.com/$photo_server/{$photo_id}_{$ph

#
# Formulate URL to the photo's Flickr page
#
$pageUrl = "http://www.flickr.com/photos/$user_id/$photo_id/";

#
# Get photo info
#
$response = $api->callMethod('flickr.photos.getInfo',
array( 'photo_id' => $photo_id ));
if (!$response)
{
print "Error getting most recent photo: ".$api->getErrorMessag
exit;
}

#
# Get title
#
$photo = $response->getElement(array(0));
$title = $photo->getElement(array(1));
$title = $title->content;

#
# Get date uploaded
#
$dateuploaded = $photo->getAttribute('dateuploaded');
$ltime = localtime((int) $dateuploaded, 1);
$datestr = $dateuploaded;

$datestr = sprintf('%4d-%02d-%02d %2d:%02d',


$ltime['tm_year']+1900,
$ltime['tm_mon']+1,
$ltime['tm_mday'],
$ltime['tm_hour'],
$ltime['tm_min']);

#
# Join tags into a single string
#
$tags = $photo->getElement(array(8));
$n = 0;
$taglist = '';
foreach ($tags->children as $tag)
{
if ($n++ > 0)
$taglist .= ', ';
$taglist .= $tag->content;
}

#
# Output HTML page containing URL to photo, image, and tags.
#
print <<<EOT
<html>
<head>
<title>Sample Photo Page</title>
</head>
<body>
<center>
The latest from $username...<br>
<a href="$pageUrl"><img src="$imgUrl" /></a><br>
Title: $title<br>
Uploaded: $datestr<br>
$taglist
</center>
</body>
</html>
EOT;

?>

T he final s ec tion of this program outputs the s ame H T M L as the


P erl programs in [Hack #38] . To us e the program, upload it to
your web s erver and type in its U RL . T he res ult will be s ame as
in Figure 6 - 3 .
Viewing a User's Latest Photo Using
phpFlickr

T his next program is a port of the previous one with exac tly the
s ame features . T he only differenc e is that it us es phpFlickr,
whic h is a higher- level A P I kit than PEAR::Flickr_API. I think
you'll find the c ode eas ier to unders tand. I n addition, the s upport
web s ite for phpFlickr c ontains c ons iderably more doc umentation
and a few ac tual c ode examples . H uzzah!

<?

# getLastPhoto - phpFlickr version

require_once("phpFlickr.php");

$api_key = 'your_api_key';

$api = new phpFlickr($api_key);

# This is a good spot to enable caching -- see the ransom note hac
# in Chapter 7 for an example

#
# Get user's ID
#
$username = 'jbum';
if (isset($_GET['username']))
$username = $_GET['username'];
$user_id = $api->people_findByUsername($username);

#
# Get user's most recent photo
#

$photos = $api->people_getPublicPhotos($user_id,NULL,1);

$photo = $photos['photo'][0];
$photo_id = $photo['id'];
$photo_secret = $photo['secret'];
$photo_server = $photo['server'];

#
# Formulate URL to the photo (image)
#
$imgUrl = "http://static.flickr.com/$photo_server/{$photo_id}_{$ph

#
# Formulate URL to the photo's Flickr page
#
$pageUrl = "http://www.flickr.com/photos/$user_id/$photo_id/";

#
# Get Photo Info
#
$photoInfo = $api->photos_getInfo($photo_id);

#
# Get title
#
$title = $photoInfo['title'];

#
# Get date uploaded
#
$dateuploaded = $photoInfo['dateuploaded'];
$ltime = localtime($dateuploaded, 1);
$datestr = $dateuploaded;
$datestr = sprintf('%4d-%02d-%02d %2d:%02d',
$ltime['tm_year']+1900,
$ltime['tm_mon']+1,
$ltime['tm_mday'],
$ltime['tm_hour'],
$ltime['tm_min']);

#
# Join tags into a single string
#
$tags = $photoInfo['tags'];
$n = 0;
$taglist = '';
foreach ($photoInfo['tags']['tag'] as $tag)
{
if ($n++ > 0)
$taglist .= ', ';
$taglist .= $tag['_value'];
}

#
# Output HTML page containing URL to photo, image, and tags.
#
print <<<EOT
<html>
<head>
<title>Sample Photo Page</title>
</head>
<body>
<center>
The latest from $username...<br>
<a href="$pageUrl"><img src="$imgUrl" /></a><br>
Title: $title<br>
Uploaded: $datestr<br>
$taglist
</center>
</body>
</html>
EOT;

?>

C omparing the two programs , you'll s ee that phpFlickr has an


individual func tion for eac h A P I c all that returns a data s truc ture
that is hand- tailored for that c all. For example:

$user_id = $api->people_findByUsername($username);
...
$photos = $api->people_getPublicPhotos($user_id,NULL,1);
...
$photoInfo = $api->photos_getInfo($photo_id);

T his makes the c ode more readable, but it als o means that
phpFlickr is c los ely tied to the partic ular s tate of the A P I at the
time it was releas ed. I f a new c all is added to the A P I , phpFlickr
won't s upport it until it is updated to add new glue. A t the
moment, however, things are pretty s table, and D an C oulter (the
developer of phpFlickr) has been pretty attentive to updates .

Bec aus e of its eas e of us e, phpFlickr is a great c hoic e for mos t


of your P H P - related Flic kr projec ts , and you'll s ee it c rop up a
few more times in this book.
See Also

[Hack #37]

[Hack #38]

[Hack #41]

[Hack #47]
Hack 40. Authenticate Yourself

For single-user apps, authentication isn't all that complicated.

Flic kr has a nifty little A P I method c alled


flickr.photos.transform.rotate that c an rotate a photo by 9 0 ,
1 8 0 , or 2 7 0 degrees . T his is a c ool thing to do, but it's probably
not s omething you want other people doing to your photos . I t
would be kind of annoying to s ign into Flic kr only to dis c over all
your photos ups ide down! T his is why this method, and a few
others like it, requires authentic ation: it allows you, the us er, to
c ontrol whic h apps get to do annoying things to your photos .

H owever, this als o means that if you are the author of an app,
and you are the only pers on us ing the app, you'll s till need to
jump through the hurdle of giving your app permis s ion to ac c es s
your own photos . A t the time of this writing, Flic kr's older,
eas ier- to- us e authentic ation mec hanis m s till works : you c an
pas s your email addres s and pas s word as parameters to any
Flic kr A P I c all that requires authentic ation. But this method is
c urrently being phas ed out, bec aus e it is n't very s ec ure.

Flic kr is now phas ing in a more c umbers ome but more s ec ure
authentic ation A P I . T his hac k s hows a relatively s imple way to
authentic ate your own apps , us ing this new A P I , for your own
private us e. T his method involves only a tiny bit of s c ripting and
is us eful for s ituations in whic h you are the only one who will be
us ing the app.
I f you want to authentic ate us ers other
than yours elf, s ee [Hack #41] .

Authentication Modes

Your applic ation c an us e one of three different authentic ation


proc edures or modes . D oc umentation des c ribing the three
authentic ation modes c an be found at
http://www.flic kr.c om/s ervic es /api/mis c .us erauth.html.

E ac h of the three authentic ation modes is a proc edure that


ac c omplis hes the s ame thing: they eac h produc e an
authentic ation token. T his token is pas s ed as a parameter to
A P I c alls that require authentic ation, s uc h as
flickr.groups.pools.remove.

Flic kr us es the token to figure out whic h Flic kr us er is us ing your


app and what permis s ions that us er has granted to your app. T he
differenc es in the proc edures of eac h mode are due to the nature
of the apps for whic h they are intended to be us ed.

Web Applications

T his authorization mode is intended to be us ed by apps that are


hos ted on web s ervers . I t provides a more s eamles s
navigational path. I f your app needs authorization, it
automatic ally redirec ts the us er to a Flic kr- hos ted web page, in
whic h the us er grants permis s ions before being automatic ally
direc ted bac k to your app.

Flic kr pas s es s ome information bac k to your app (the frob,


des c ribed later in this hac k), whic h is then us ed to obtain the
authorization token. T his is the bes t mode to us e if your app is
running on a web s erver and is us ed by more than one pers on. I t
provides the bes t eas e of us e from the us er's point of view, but
it's probably the hardes t of the three modes for the programmer
to implement (although a number of the A P I toolkits that are
available, s uc h as phpFlic kr [Hack #41], s implify this
c ons iderably).

Desktop Applications

T his authorization mode is s imilar to the Web A pplic ations mode,


but it's des igned for s tandalone (des ktop) applic ations in whic h
there is no direc t navigational path bac k to the applic ation from
the authentic ation page. T herefore, the proc edure does n't
require that Flic kr return a frob bac k to the c alling applic ation,
as the Web A pplic ations proc edure does .

I ns tead, the app reques ts the frob before the us er is s ent to the
Flic kr- hos ted permis s ions page, us ing the Flic kr A P I
flickr.auth.getFrob method. T his way, when the us er grants
permis s ion on Flic kr, the app already has all the information it
needs to generate an authentic ation token.
Mobile Applications

T his is the mos t rudimentary of the authentic ation modes , and


it's the one we'll us e for authentic ating yours elf. I t is intended to
be us ed on mobile devic es and provides an authentic ation page
that is formatted for the s mall s c reens on thes e devic es .

T he s implic ity of this method als o makes it ideal for c ommand-


line apps or apps that have only a s ingle us er, s uc h as apps you
write for your own private us e. T his is a good authentic ation
mode to us e for bot s c ripts that adminis ter groups on Flic kr, s uc h
as the one developed in [Hack #36] .

Frobs and Mini-Tokens

E ac h of the previous authentic ation modes generates a random-


looking s tring, whic h is not the token but is us ed to obtain the
token. I n the Web A pplic ations and D es ktop A pplic ations
modes , this s tring is c alled a frob (H ac keres e for "a little random
thing- a- ma- bob"). Your app c onverts the frob into a token by
is s uing the A P I method flickr.auth.getToken.

T he M obile A pplic ations authentic ation mode does s omething


s imilar, but ins tead of generating a frob, it generates a mini-
token, whic h is bas ic ally the s ame thing as a frob, but s horter, s o
it'll fit in a s maller s pac e (s uc h as the s c reen of a c ell phone). A
mini- token is c onverted into an authentic ation token via the A P I
method flickr.auth.getFullToken. T he authentic ation tokens
returned by flickr.auth.getToken and flickr.auth.getFullToken are
the s ame thing; what's different are the frobs and mini- tokens
us ed to obtain them.
O nc e you've obtained an authentic ation token (us ing either a
frob or a mini- token), you c an c ontinue us ing it indefinitely.
Tokens don't expire unles s the us er c hanges the permis s ions .
U s ers c an remove the permis s ions for any of the apps they've
granted permis s ion by vis iting
http://www.flic kr.c om/s ervic es /auth/lis t.gne.

Getting Started

Firs t, get an A P I key for your app, if you haven't already. Sign in
to Flic kr and go to the following U RL :

http://www.flic kr.c om/s ervic es /api/

C lic k the A P I Keys link (under "Read thes e firs t:"), and then
c lic k the "A pply for your key online now" link. For more
information about getting an A P I key, s ee "A P I Keys and
Sec rets ," earlier in this c hapter.

A fter you get your A P I key, you'll need to get your s hared s ec ret
and authentic ation U RL . Reload the A P I s ervic es page
(http://www.flic kr.c om/s ervic es /api/) and c lic k the word "Yours "
on the line that s ays "A P I Keys (Yours )."

T his will take you to the following U RL :

http://www.flic kr.c om/s ervic es /api/regis tered_keys .gne

You'll s ee a lis t of all your A P I keys , one for eac h app, as s hown
in Figure 6 - 4 .

Figure 6-4. Your API keys


Your new app will appear at the top of the lis t, s inc e you jus t
ac quired the A P I key. I f you don't s ee it there, wait a minute and
reload the page.

To the right will be a link that s ays "A uthentic ation: N ot


c onfigured." (I f you've already done this onc e, the link will read
"A uthentic ation: E dit c onfiguration.") C lic k this link to c onfigure
your authentic ation, as s hown in Figure 6 - 5 .

Figure 6-5. API Key Authentication Setup screen


Fill out this form, giving your app a title and des c ription. For
A uthentic ation Type, c hoos e M obile A pplic ation. T here are two
piec es of information on this form to rec ord in your text file. A t
the top, it will s how you the s hared s ec ret:

Shared secret: 8698bb062a08ca11

A t the bottom, it will s how the authentic ation U RL for granting


permis s ions to your app:

Your authentication URL is http://www.flickr.com/auth-6192.

P as te the authentic ation U RL into your brows er's addres s bar,


and pres s Return to bring up the s c reen s hown in Figure 6 - 6 .

Figure 6-6. Authentication request screen


P res s the button that s ays "O K, I 'll A llow I t." You'll be taken to
the page s hown in Figure 6 - 7 , whic h dis plays a mini- token.

Figure 6-7. Authorization success screen with


mini-token
C opy the mini- token into the text file c ontaining your A P I key
and s hared s ec ret.

The Code

N ow, you'll need to us e flickr.auth.getFullToken to c onvert the


mini- token into a full token. T his is the only s tep that requires
programming, but not a hec k of a lot of it, s inc e we'll be us ing the
Flickr::API P erl module.

T he following P erl s c ript makes us e of two public ly available


modules : Flickr::API and XML::Simple. I f you're mis s ing a
module, you c an ins tall it from C P A N , like this :

> perl -MCPAN -e shell


cpan> install XML::Simple
C reate a file c alled getFullToken.pl and add this c ode:

#!/usr/bin/perl

# Convert Mini-Token to a Full Token - Jim Bumgardner

use Flickr::API;
use XML::Simple;

# This information is provided on the command line


#
#
$api_key = shift;
$shared_secret = shift;
$mini_token = shift;

die "Syntax: getFullToken.pl api_key shared_secret mini_token\n" i

my $api = new Flickr::API({key => $api_key, secret => $shared_secr


my $response = $api->execute_method('flickr.auth.getFullToken',{mi
die ("GetFullToken Failed: " . $response->{error_message} . "\n" )

$auth_token = XMLin($response->{_content})->{auth}->{token};
print "auth_token: $auth_token\n";

# This is commented out but is useful for debugging problems


# with this type of script.
# I used it to figure out how to extract the $token field.
#
# use Data::Dumper;
# print Dumper($response);
exit;
Running the Hack

To run the hac k, you'll need the information we c ollec ted in the
prec eding s teps . I n our example, the values are:

928c994908f02385d1d97a457003cb71
A P I key

8698bb062a08ca11
Shared s ec ret

248-818-201
M ini - token

Type the s c ript's name followed by thes e three parameters on


the c ommand line to get the full authentic ation token:

> GetFullToken.pl 928c994908f02385d1d97a457003cb71 8698bb062a08ca1


auth_token: 127122-92395db066e82035

A dd the authentic ation token to the c ollec tion of information you


have s aved. You c an now is s ue A P I c alls that require
authentic ation us ing thes e three piec es of information
(s ubs titute in your own values ):

928c994908f02385d1d97a457003cb71
A P I key

8698bb062a08ca11
Shared s ec ret

127122-92395db066e82035
A uthentic ation token

You c an rec ord this information direc tly in your app and us e the
app indefinitely, as long as you don't revoke your own
permis s ions .

H owever, a better s ys tem is to rec ord thes e fields in a s eparate


file and inc lude it in the applic ationfor example, us ing P erl's
require c ommand. T his way, the authentic ation information is
s tored s eparately from your applic ation s ourc e c ode, and you
c an s hare the applic ation s ourc e c ode more eas ily. T his is the
tec hnique us ed in [Hack #36], whic h us es thes e authentic ation
parameters in a s c ript for Flic kr group adminis tration.

See Also
[Hack #41]

[Hack #36]
Hack 41. Authenticate Users

phpFlickr takes most of the grunt work out of authentication.

A uthentic ating people is one of the more has s le- prone features
of the A P I . T his is why it's a good idea to us e an A P I wrapper: it
handles the nitty- gritty details .

For P H P programmers , D an C oulter's phpFlickr does this job


admirably well. I 've found it to be the mos t well s upported of the
P H P wrappers c urrently available for Flic kr. I t even has its own
web s ite, with doc umentation and example c ode, loc ated at
http://www.phpFlic kr.c om.

T his hac k c reates a web applic ation that dis plays a few of a
us er's mos t rec ent photos . We'll us e authentic ation s o that we
c an dis play the us er's P rivate photos as well as P ublic photos .

What You Need

T hes e s c ripts were written for P H P 4 , s o you'll need a web


s erver with P H P 4 s upport.

You'll als o need the phpFlickr pac kage of A P I wrappers , whic h is


available from http://www.phpFlic kr.c om. T he pac kage inc ludes
the following:
phpFlickr.php

T his is the main s ourc e c ode file for phpFlickr. T he


remaining files are s upport files that are referenc ed from
within phpFlickr.php.

auth.php

T his is a s ample c allbac k s c ript for authentic ation that


D an provides . We'll be making s ome modific ations to it.

xml.php

T his s ourc e file, written by A aron C olfles h, provides an


XM L pars er that is us ed by phpFlickr.

PEAR/

T his direc tory c ontains s ourc e c ode for P E A R databas e


ac c es s , whic h is us ed to implement phpFlickr's optional
c ac hing feature. I highly rec ommend that you ins tall this
c ode and us e c ac hing, bec aus e it will greatly improve
the performanc e of phpFlickr and reduc e the load on
Flic kr.

T he phpFlickr arc hive als o inc ludes s ome additional files that
s erve as s ample c ode and are not s tric tly required for a
phpFlickr ins tallation. You s hould ins tall all of the prec eding files
and the PEAR/ direc tory to a loc ation where P H P c an find them,
s uc h as in the php_include path. You might find it s imples t, at
firs t, to keep thes e files in the s ame direc tory as the firs t tes t
applic ation you write.
Getting Started

Firs t, get a new A P I key for the new app, following the
ins truc tions in "A P I Keys and Sec rets ."

A fter you've been is s ued the A P I key, you'll want to c onfigure


the new app for web authentic ation. Reload the A P I s ervic es
page (http://www.flic kr.c om/s ervic es /api/), and c lic k the word
"Yours " on the line that s ays "A P I Keys (Yours )."

T his will take you to the following U RL :

http://www.flic kr.c om/s ervic es /api/regis tered_keys .gne

You'll s ee a lis t of all your A P I keys , one for eac h app, as s hown
in Figure 6 - 8 .

Figure 6-8. Your API keys


Your new app will appear at the top of the lis t, s inc e you jus t
ac quired the A P I key. I f you don't s ee it there, wait a minute and
reload the page.

To the right will be a link that s ays "A uthentic ation: N ot


c onfigured." C lic k on this link to c onfigure your authentic ation.
A fter you've done this onc e, the link will read "A uthentic ation:
E dit c onfiguration."

A fter c lic king the link, fill out the form, as s hown in Figure 6 - 9 .

Figure 6-9. API Key Authentication Setup screen


For A uthentic ation Type, s elec t Web A pplic ation. For C allbac k
U RL , enter the U RL where you ins talled (or plan to ins tall)
auth.php. You'll find your s hared s ec ret at the top of the page.
C opy it, and c lic k Save C hanges to s et the authentic ation.

The Code

C reate a file c alled tes tauth.php and add the following c ode:

<?php

// testauth.php - based on code by Dan Coulter


//
//

ini_set("error_reporting ", E_ALL);

// Configuration stuff
$flickrAPIKey = "your API key goes here";
$flickrSharedSecret = "your shared secret goes here";

// Caching configuration stuff


$cachingenabled = false;
$dbUser = "your database username";
$dbPass = "your database password";
$dbAddress = "your database domain name (or localhost)";
$dbTable = "database table name";

// Create new phpFlickr object


require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey,$flickrSharedSecret);
if ($cachingenabled == true)
{
$f->enableCache(
"db",
"mysql://$dbUser:$dbPass@$dbAddress/$dbTable");
}
$f->auth( );
$token = $f->auth_checkToken( );

// Parse parameters
$page = 1;
if (isset($_GET['page']))
$page = $_GET['page'];

$columns = 6;
if (isset($_GET['columns']))
$columns = $_GET['columns'];

$rows = 6;
if (isset($_GET['rows']))
$rows = $_GET['rows'];

$per_page = $columns * $rows;

// Find the NSID of the username inputted via the form


$nsid = $token['user']['nsid'];

// Get the friendly URL of the user's photos


$photos_url = $f->urls_getUserPhotos($nsid);

// Get the user's first 36 public photos


$photos = $f->photos_search(array("user_id" => $nsid, "per_page" =
// Loop through the photos and output the HTML
$i = 0;
foreach ($photos['photo'] as $photo) {
echo "<a href=$photos_url$photo[id]>";
echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "Square") . ">";
echo "</a>";
$i++;
// If it reaches the sixth photo, insert a line break
if ($i % $columns == 0) {
echo "<br>\n";
}
}

?>

You'll need to modify the c onfiguration s ec tion at the top.


C hange the flickrAPIKey and flickrSharedSecret variables to your
ac tual A P I key and s hared s ec ret. I f you intend to us e databas e
c ac hing (and I highly rec ommend it, bec aus e it will make your
app zippier), you'll need to edit the databas e- related variables
as well. H ere are the c onfiguration lines , s howing s ample values :

// Configuration stuff
$flickrAPIKey = "928c994908f02385d1d97a457003cb71";
$flickrSharedSecret = "8698bb062a08ca11";

// Caching configuration stuff


$cachingenabled = true;
$dbUser = "krazydad";
$dbPass = "ignatiusluvsdonuts";
$dbAddress = "localhost";
$dbTable = "myflickrbase";
A fter editing the c onfiguration, s ave the file.

You will als o need to make s imilar modific ations to auth.php. A dd


your A P I key and s hared s ec ret to thes e two lines :

$api_key = "[your API key]";


$api_secret = "[your API secret]";

N ow, upload both tes tauth.php and the modified vers ion of
auth.php to your web s erver. You're ready to tes t your app!

Running the Hack

E nter the addres s of the P H P file in your web brows er's addres s
bar, like s o:

http://www.yourdomain.com/testauth.php

T he firs t time you do this , the routine f->auth() will notic e that
there is no authentic ation token for you and will redirec t you to
the Flic kr applic ation permis s ions page, whic h looks s omething
Figure 6 - 1 0 .

Figure 6-10. Flickr's application permissions


page
When phpFlickr redirec ts you to this page, it adds a parameter,
exTRa, that c ontains the U RL of your tes t applic ation.

A fter you pres s the "O K, I 'll A llow I t" button, you'll be
redirec ted bac k to the auth.php applic ation. T he exTRa parameter
will be pas s ed bac k, s o that auth.php knows where to ultimately
redirec t you.

T he auth.php app will c onvert the frob [Hack #40] to a full


authentic ation token and s tore it in the P H P s es s ion variables ;
then, it will redirec t you bac k to tes tauth.php. When tes tauth.php
runs again, it will retrieve the authentic ation token from the
s es s ion variables , and the app will finally be able to make A P I
c alls that require authentic ation.

A s a us er, fortunately, all this magic happens under the hood.


T he apparent res ult of pres s ing the "O K, I 'll A llow I t" button is
that your pic tures will s tart appearing on the s c reen, as s hown in
Figure 6 - 1 1 .

Figure 6-11. A test run of testauth.php


C ongratulations , you've been authentic ated! N ow, any other
us ers who vis it this web page c an authentic ate thems elves in
the s ame way, eas ily and painles s ly... at leas t, for them!

See Also

[Hack #40]

[Hack #14]
Hack 42. Build a Custom Upload Script

If the existing Flickr upload tools aren't your cup of tea, try
brewing your own upload script.

T he Tools page at Flic kr (http://www.flic kr.c om/tools /) points to a


number of different programs that are available to help you
upload your photos to Flic kr [Hack #5]. M any inc lude s ome
extra features , s uc h as the ability to add tags , s et photo privac y
options , and res ize photos . But if the exis ting tools don't quite fit
with how you want to upload photos , you c an c reate your own
upload program, thanks to the Flic kr A P I .

Say you perform a c ertain number of s teps for eac h photo that
you upload to Flic kr. With s ome automation, you s hould be able
to c ombine thos e s teps with the upload proc edure, s aving you
time in the proc es s . T his hac k s hows how to put together a
c us tom upload s c ript that res izes photos and adds a c opyright
notic e before s ending them off to Flic kr. You c an adapt it to s uit
your needs .

Authorizing Your Script

T he firs t s tep to c reating a c us tom upload s c ript is giving your


s c ript the authority to add photos to your Flic kr photos tream.
T he Flic kr A P I has a us er authentic ation s ys tem [Hack #40]
that makes s ure only authorized programs c an add, edit, or
delete photos at Flic kr.

T he key to authorizing your own s c ript is reques ting an


authentication tokena s tring of c harac ters that repres ents your
unique c ombination of us er I D and A P I key. You'll als o need a
s pec ial s tring c alled a s hared s ecret, whic h you c an pic k up when
you c onfigure your A P I key. T his s tep is a bit of a has s le, but it
ens ures your s ec urity. P lus , it's a one- time proc es s ; onc e you
have your authentic ation token, you won't need to reques t one
again (for this applic ation, anyway).

To get s tarted, go to the Flic kr A P I page


(http://www.flic kr.c om/s ervic es /api/) and reques t a unique A P I
key by c lic king the A P I Keys link on the left s ide of the page.
N ote that even if you have an A P I key for another applic ation,
you'll want to reques t a unique key for eac h applic ation you
c reate. O nc e you have the key, be s ure to c opy it to a s afe
plac e. T hen, go bac k to the Flic kr A P I page and c lic k the Yours
link in parenthes es next to the A P I Keys link.

O n the regis tered keys page, you'll s ee a lis t of all your A P I


keys . E ac h key has an authentic ation c onfiguration. C lic k the
"N ot c onfigured" link as s oc iated with your new key to s et it up.

O n the A P I Key A uthentic ation Setup page, you'll find your key
and your s hared s ec ret, and you c an s pec ify a title, des c ription,
logo, U RL , and authentic ation type for your applic ation. Bec aus e
you're authentic ating an applic ation for yours elf only, you don't
need to worry too muc h about what you enter here. G ive your
applic ation a memorable name s uc h as "M y U pload Sc ript," and
c hoos e D es ktop A pplic ation as the A uthentic ation Type. C opy
your s hared s ec ret, and c lic k Save C hanges to s et the
authentic ation.

T he following s c ript will reques t an authentic ation token for your


s c ript. You'll need the nons tandard modules Flickr::API
(http://s earc h.c pan.org/~iamc al/Flic kr- A P I -
0 .0 7 /lib/Flic kr/A P I .pm) and XML::Simple
(http://s earc h.c pan.org/~grantm/XM L- Simple-
2 .1 4 /lib/XM L /Simple.pm) for working with A P I res pons es , and
Digest::MD5 (http://s earc h.c pan.org/~s imkin/A pac he-
L oggedA uthD BI - 0 .1 2 /M D 5 .pm) for formatting reques ts .

C opy the following c ode to a file c alled get_auth_token.pl, and be


s ure to inc lude your Flic kr A P I key and s hared s ec ret at the top
of the s c ript:

#!/usr/bin/perl
# get_auth_token.pl
# This script requests an authentication token for a user
# given a specific API key and shared secret.
#
# You can get a Flickr API key and shared secret and read the
# full documentation for the Flickr API at:
#
# http://www.flickr.com/services/api/

use strict;
use Flickr::API;
use XML::Simple;
use Digest::MD5 qw/md5_hex/;

# Set your Flicker variables


my $api_key = 'insert Flickr API key';
my $shared_secret = 'insert Flickr shared secret for API key';
my $permission_wanted = 'write';

# Start the API


my $api = new Flickr::API({'key' => $api_key,
'secret' => $shared_secret});
my $response = $api->execute_method('flickr.auth.getFrob');
# Grob the frob
my $xmlsimple = XML::Simple->new( );
my $flickr_xml = $xmlsimple->XMLin($response->{_content});
my $frob = $flickr_xml->{frob};

# Get authorization for read access


my $url = $api->request_auth_url($permission_wanted, $frob);

# Open browser with auth URL (Windows only!)


$url =~ s/&/^&/gis; #Escape URL for command line
system "start $url";

# Non-Windows systems should print out the URL


# print "Go to the following URL in a web browser:\n\n$url\n\n";

# Tell the user to check out the Flickr window


print "Return to this window after you've finished the authorizati
<STDIN>;

# Get the auth token


my $response = $api->execute_method('flickr.auth.getToken', {
'frob' => $frob});
my $flickr_xml = $xmlsimple->XMLin($response->{_content});

my $auth_token = $flickr_xml->{auth}->{token};
die "Couldn't get authentication token!" unless defined $auth_toke

print "\nYour auth token is: $auth_token";

You c an run the s c ript by c alling it on the c ommand line:

perl get_auth_token.pl
T he s c ript will c ontac t the Flic kr A P I and as s emble the U RL for
reques ting authorization. I t will then open a brows er window with
that U RL , and you'll need to log in and grant your applic ation
permis s ion to read and write photos .

T he system "start $url"; c ommand in this


s c ript will open a brows er with the
s pec ified U RL on Windows s ys tems only. I f
you're us ing a M ac , you c an us e the system
"open $url"; c ommand. I n a U nix
environment, c omment out this line and
unc omment the line that prints out the
U RL . You'll need to c opy and pas te the
U RL into your brows er's addres s bar.

O nc e you've granted the applic ation permis s ion, return to the


c ommand window and hit E nter. You s hould rec eive a s tring of
c harac ters that repres ents your authentic ation token. C opy
down this s tring, and you'll be ready to build your c us tom s c ript.

The Code

T he following c ode looks for any photos in a s pec ial Flickr drop
folder, res izes the photos , adds a c opyright notic e to eac h of
them, and uploads them automatic ally. O nc e uploaded, the
photos are moved to a Flickr s ent folder. You'll need to s et the
$flickrdrop and $flickrsent variables to folders on your s ys tem.

T he c opyright notic e c an be any s tring of text; jus t s et the


$copyright variable to s omething like Copyright 2005 Paul Bausch.
You'll als o need to s et the $maxsize variable, whic h repres ents
the maximum s ize in pixels you want to uploadthis c an help you
get the mos t out of your Flic kr bandwidth limit [Hack #4]. T his
image proc es s is handled by the Image::Magick module, whic h
you'll want to be s ure is ins talled on your s ys tem. You c an
download I mageM agic k from http://www.imagemagic k.org; be
s ure to ins tall the P erlM agic k module when you ins tall the
program.

T he final piec e you'll need is the Flickr::Upload module


(http://s earc h.c pan.org/~c pb/Flic kr- U pload- 1 .2 2 /U pload.pm),
whic h you c an ins tall with C P A N . T his module enc aps ulates all
of the nec es s ary Flic kr A P I c alls into a s ingle handy upload()
func tion.

C opy the following c ode to a file c alled flickr_upload.pl, and be


s ure to inc lude your Flic kr A P I key, s hared s ec ret, and rec ently
ac quired auth token:

#!/usr/bin/perl
# flickr_upload.pl
# This script loops through photos in a directory, resizes each
# photo to the set maximum size, adds a copyright notice to each
# photo, and uploads each photo to Flickr. You can also specify a
# number of tags to associate with each photo on the command line.
#
# Usage: flickr_upload.pl [tag] [tag] [tag]
#
# You'll need an auth token, which you can aquire by running the
# accompanying get_auth_token.pl script.
#
# You can get a Flickr API key and shared secret and read the
# full documentation for the Flickr API at:
#
# http://www.flickr.com/services/api/

use strict;
use Flickr::Upload;
use Image::Magick;
use File::Copy;

# Set your environment variables


my $flickrdrop = 'c:/flickrDrop/';
my $flickrsent = 'c:/flickrDrop/sent/';
my $copyright = 'insert your copyright notice';
my $maxsize = 500;

# Set your Flickr variables


my $api_key = 'insert Flickr API key';
my $shared_secret = 'insert Flickr shared secret for API key';
my $auth_token = 'insert Flickr auth token';

# Grab any tags on the command line


my $tags = join(' ', @ARGV);

# Start the Flickr Uploader


my $ua = Flickr::Upload->new({'key'=>$api_key,'secret'=>$shared_se

# Open the Flickr drop directory and grab .jpg files


my @IDs;
opendir(DIR, $flickrdrop) || die "Cannot open directory: $flickrdr
my @photos = grep { /.jpg/i } readdir DIR;
closedir DIR;
@photos = sort @photos;
foreach my $photo (@photos) {

# Tell user which photo is going


print "Uploading $photo...";

my $photopath = "$flickrdrop$photo";

# Read the photo and get the size with Image::Magick


my $image = new Image::Magick;
$image->Read($photopath);

my $width = $image->Get('width');
my $height = $image->Get('height');

# Resize the photo with Image::Magick if necessary


if ($height > $width) {
if ($height > $maxsize) {
my $new_height = $maxsize;
my $new_width = $width * ($maxsize / $height);
$image->Resize(
width=>$new_width,
height=>$new_height,
blur=>0.5,
filter=>'Box');
print "Resized...";
}
} else {
if ($width > $maxsize) {
my $new_width = $maxsize;
my $new_height = $height * ($maxsize / $width);
$image->Resize(
width=>$new_width,
height=>$new_height,
blur=>0.5,
filter=>'Box');
print "Resized...";
}
}

# Add copyright information to the photo with Image::Magick


$image->Annotate(
font=>'c:/windows/fonts/verdanab.TTF',
pointsize=>11,
fill=>'white',
text=>$copyright,
gravity=>'SouthEast',
antialias=>1,
translate=>5,5);

# Save the photo with changes


$image->Write($photopath);

# Upload the photo to Flickr


my $photoid = $ua->upload(
'photo' => $photopath,
'auth_token' => $auth_token,
'tags' => $tags,
'is_public' => 1,
'is_friend' => 1,
'is_family' => 1,
'async' => 0,
) or warn "Couldn't upload $photo\n";

if ($photoid ne '') {
# Tell the user this photo is at Flickr
print "Done!\n";

# Store the Flickr ID in an array


push(@IDs, $photoid);
# Copy photo to the sent folder
copy($photopath, "$flickrsent$photo")
or die "Can't copy $photo.";

# Delete the original photo


unlink($photopath);
}
}

# Build the review images URL


my $flickrURL = "http://www.flickr.com/tools/uploader_edit.gne?ids
foreach my $id (@IDs) {
$flickrURL .= $id . ",";
}

# Open browser with the review images URL (Windows only!)


system "start $flickrURL";

A s eac h photo in the folder is proc es s ed and s ent to Flic kr, the
s c ript s tores eac h photo's new Flic kr I D in the @IDs array. A t the
end of the proc es s , the s c ript builds a U RL that will let you edit
the title, des c ription, and tags of eac h of the newly uploaded
photos .

Windows us ers will s ee the page in their brows er, thanks to the
final system " start $flickrURL"; c ommand. I f you're working in
another environment, you might want to s imply print the U RL to
the c ommand prompt, like s o:

print $flickrURL;
Running the Hack

To proc es s a batc h of photos with the s c ript, c opy the photos to


the s pec ified Flic kr drop folder and run the s c ript from a
c ommand prompt, like this :

perl flickr_upload.pl

Be s ure to put c opies of the photos in the


Flic kr drop folder, rather than the original
photos . P roc es s ing a photo c ould
s ignific antly alter the file, and without a
bac kup, you'll los e the ability to go bac k to
the original vers ion.

You c an als o s pec ify tags as you run the s c ript. For example, if
you know you jus t dumped a bunc h of photos of trees into the
Flic kr drop folder, you c ould automatic ally tag eac h photo like
this :

perl flickr_upload.pl tree green leaves


O nc e at Flic kr, eac h photo will have the tags tree, green, and
leaves .

Figure 6 - 1 2 s hows a photo at Flic kr with the c opyright notic e


added to the lower- right c orner.

Figure 6-12. Image uploaded and processed


with a custom script
E ac h photo is moved to the Flic kr s ent folder onc e it's uploaded,
s o when the s c ript is finis hed, the Flic kr drop folder will be ready
for another batc h of photos to proc es s . A new brows er window
will open, s o you c an review all of the photos you uploaded and
add titles , des c riptions , and tags if nec es s ary.

Building your own upload s c ript takes a bit of time, but if you c an
enc aps ulate photo proc es s ing and Flic kr uploading into one
s tep, you'll make up that time eas ily in the future. A nd you'll
have a s c ript that's tailor- made for you!
Chapter 7. Custom
Applications
H ac ks 4 3 - 5 0

H ac k 4 3 . M as h U p Your P hotos

H ac k 4 4 . Find the D ominant C olor of an I mage

H ac k 4 5 . M ake a C olor P ic ker

H ac k 4 6 . M ake a M otivational P os ter and O ther Swag

H ac k 4 7 . M ake a Rans om N ote

H ac k 4 8 . M ake a Slider P uzzle

H ac k 4 9 . M ake a P hoto M os aic

H ac k 5 0 . M ake a Slides how


Hacks 43-50
M any independent developers have taken photos beyond the
Flic kr web s ite and into c ompletely new applic ations , thanks to
the Flic kr A P I . I n the s ame s pirit of s haring, they've made their
c us tom Flic kr apps available to anyone who wants to play with
them.

Some of thes e Flic kr toys c an turn your photos into motivational


pos ters [Hack #46] or puzzles [Hack #48] . With a bit of
programming, you c an als o mas h up Flic kr photos into c ollages
[H ac k #4 3 ], rans om notes [Hack #47], or c omplex photo
mos aic s [Hack #49] .

T his c hapter will s how you what's pos s ible when you go beyond
the Flic kr A P I bas ic s into the realm of more fully realized
c us tom applic ations .
Hack 43. Mash Up Your Photos

ImageMagick is the ultimate tool f or making collages.

T his is the firs t in a s eries of hac ks about c reating mos aic


images . I n this hac k, we'll build an image that c ontains a number
of other photographs , randomly pos itioned and rotated. I n the
c ours e of doing this , we'll learn a bit about the inc redibly us eful
I mageM agic k library (plus , we'll make a pretty interes ting-
looking c ollage).

What You Need

To build a c ollage from Flic kr images , you'll need s ome Flic kr


images , of c ours e. I like to work with 1 0 0 x 1 0 0 thumbnails
(thes e are the ones with the _t extens ion) until I 'm happy with
the final res ult. T hen, I download larger images for the final draft.

T his hac k relies on the getP hotoL is t.pl s c ript [Hack #33] and
the getSnaps .pl s c ript [Hack #34] .

Finally, you'll need I mageM agic k and the Image::Magick P erl


module. You c an obtain both of thes e from the I mageM agic k web
s ite (http://www.imagemagic k.org).

ImageMagick
I mageM agic k is a library that enables you to automate mos t
image- proc es s ing c hores nearly everything that you might
otherwis e do with P hotos hop or G imp.

I us ually work with I mageM agic k in P erl (via the Perl::Magick


module); however, I mageM agic k has A P I s for lots of other
languages , inc luding C , C ++, J ava, P ython, P H P, and Ruby.

I mageM agic k als o c omes with s ome us eful c ommand- line


programs that allow you to do many c ommon tas ks , s uc h as
image format c onvers ions .

To illus trate the power of I mageM agic k, here's a s imple P erl


program that reads an input file (s uc h as a P N G image) and
s aves it out in s ome other format (s uc h as a J P E G image):

#!/usr/bin/perl
use Image::Magick;
($infile, $outfile) = @ARGV; # read command-line arguments: infi
$image = Image::Magick->new; # create an image handle
$image->Read($infile); # load in the source image
$image->Write($outfile); # save it back out (in some other f

T his is s omething that I mageM agic k's


convert tool does very well, but this c ode
illus trates the bas ic tec hnique of opening
and s aving images .
I mageM agic k automatic ally rec ognizes c ommon image file
extens ions s uc h as .png, .gif, .j pg, .tif, and s o on. I f you us e one
of thes e extens ions for the output filename, it will automatic ally
c onvert to the appropriate format.

H ere's a program that c reates a new image, fills it with a white


bac kground, writes s ome text on it, and s aves it out:

#!/usr/bin/perl
use Image::Magick;
$image = Image::Magick->new;
$image->Set(size=>"800x600");
$image->Read('xc:white');
$image->Annotate(text=>'Hello World', x=>50, y=>50);
$image->Write('hello.jpg');

C ommands s uc h as Annotate() offer a wealth of options . H ere's a


fanc ier vers ion of the annotation in the previous program:

$image->Annotate(text=>'Hello World', x=>50, y=>50,


font=>'comicbd.ttf', pointsize=>72, style=>'oblique',
rotate=>30, antialias=>'true', fill=>'#702948');

Finally, here's a program that takes two exis ting images and
c ompos ites them together to c reate a third image (this is the
bas is of the c ollage program that we'll develop in a moment):

#!/usr/bin/perl
use Image::Magick;
$outimage = Image::Magick->new;
$outimage->Set(size=>"800x600");
$outimage->Read('xc:white');

$img = Image::Magick->new;
$img->Read("hello.jpg");
$outimage->Composite(image=>$img, x=>10, y=>10);
undef $img;

$img = Image::Magick->new;
$img->Read("hello.jpg");
$outimage->Composite(image=>$img, x=>410, y=>10);
undef $img;

$outimage->Write('hello2.jpg');

N ote the us e of undef to undefine eac h image when it's no longer


being us ed. A lthough this is n't s tric tly nec es s ary for this s ample
program, it's important for larger c ollages that us e lots of tiles ,
to reduc e memory us age.

The Code

C reate a file c alled makeCollage.pl and add the following c ode to


it:

#!/usr/bin/perl -s
#
# makeCollage.pl - Jim Bumgardner
#

use Image::Magick;
$photolist = shift;
$collageName = shift;
die "makeCollage.pl [-big] <photolist_file> [collagename]\n" if !$

$collageName = $photolist if !$collageName;


$collageName =~ s/\.ph// if $collageName =~ /\.ph$/;

$photolist .= '.ph' if !($photolist =~ /\./);

require "$photolist";

($outW,$outH) = (1024 * ($big? 2 : 1), 768 * ($big? 2 : 1));

$outimage = Image::Magick->new;
$outimage->Set(size=>"${outW}x${outH}");
$outimage->Read('xc:black');

$dirname = $photolist;
$dirname =~ s/\.ph// if $dirname =~ /\.ph$/;

$suffix = $big? '' : '_t';

$n = 0;

foreach $photo (@photos)


{
$fnam = "$dirname/$photo->{id}$suffix.jpg";
$img = Image::Magick->new;
$err = $img->Read($fnam);
die "Problem reading $fnam: $err" if $err;

$img->Resize(geometry=>'200x200') if $big;

($w, $h) = $img->Get('width','height');


# this code gives the image a random rotation & opacity
# the mask prevents the bounding rectangle on the rotated image
# from painting over the images underneath
$rot = rand( )*90-45;
$v = int(rand( )*256);
$mcolor = sprintf '#%02x%02x%02x', $v, $v, $v;
$mask = Image::Magick->new;
$mask->Set(size=>"${w}x${h}");

$mask->Read("xc:$mcolor");
$img->Rotate(degrees=>$rot,color=>'black');
$mask->Rotate(degrees=>$rot,color=>'black');

($w, $h) = $img->Get('width','height');


$x = rand( )*($outW-$w);
$y = rand( )*($outH-$h);

$outimage->Composite(image=>$img, mask=>$mask, x=>$x, y=>$y);


undef $img;
undef $mask;
print "$n...\n" if ++$n % 100 == 0;
}

$outimage->Write("collage$suffix.png");

# done

Running the Hack

To run the hac k, we'll firs t us e s ome s c ripts we developed in


[H ac k #3 3 ] and [Hack #34] .

T he following c ommand downloads a lis t of photo rec ords from


my friend Fubuki's photos tream that have the tag macro and
s aves the information about the photos into a file c alled
fubuki_macro.ph:

getPhotolist.pl -u fubuki macro

N ext, we'll download thumbnails of Fubuki's mac ro photos (us ing


the information in the fubuki_macro.ph file we jus t c reated) and
s ave them into a folder c alled ./fubuki_macro:

getSnaps.pl fubuki_macro

Finally, we'll exec ute the c ollage s c ript we c reated in this hac k:

makeCollage.pl fubuki_macro

T he s c ript reads in the information about the photos from


fubuki_macro.ph, loads in the photos thems elves (from the
./fubuki_macro s ubdirec tory), and c ompos ites them into a new
c ollage image that is s aved to the hard drive as collage_t.png.

T he res ult is a c ollage that looks s omething like Figure 7 - 1 .

Figure 7-1. A sample collage


A s you c an s ee, this s c ript produc es a pretty interes ting- looking
image. I n the s c ript, I 've given eac h image a random rotation,
us ing this line:

$rot = rand( )*90-45;

T his as s igns a rotation to eac h image from - 4 5 to +4 5 degrees .


When you rotate images in I mageM agic k, the rotated image is
c ontained within a larger s quare bounding box, whic h will be
vis ible when the image is c ompos ited. To avoid this problem,
I 've c reated an image mas k, whic h is als o rotated, s o that the
bounding box c orners don't appear in the final res ult when
images are s tac ked on top of eac h other.

When I c reate the mas k, I as s ign it a random c olor, us ing thes e


lines :

$v = int(rand( )*256);
$mcolor = sprintf '#%02x%02x%02x', $v, $v, $v;
$mask = Image::Magick->new;
$mask->Set(size=>"${w}x${h}");
$mask->Read("xc:$mcolor");

T he c olor of the mas k determines the opac ity of the image that
is being c ompos ited. I f the mas k is white (#FFFFFF), the image is
fully opaque. I f the mas k is blac k (#000000), the image is
trans parent. By us ing a range of random values for the mas k
c olor from blac k to white, we get a variety of opac ities in the final
image, whic h produc es a more impres s ionis tic res ult.

E ac h image is plac ed at a random loc ation within the c ollage by


us ing random x and y c oordinates :

$x = rand( )*($outW-$w);
$y = rand( )*($outH-$h);

I s ubtrac t the photo's width and height from the range of


pos s ible values to ens ure that the photos don't ac c identally
bleed over the right or bottom edge of the c ollage.

Sinc e this s c ript us es random numbers , your res ults won't


exac tly matc h the res ults s hown here, and you'll get different
res ults eac h time you run the s c ript. I f you want more
predic table res ults , add a line at the beginning to s eed P erl's
random number generator with a fixed value, like s o:

srand(27);

I c hos e 2 7 bec aus e it's my favorite number. Try different


numbers until you get a res ult you like.

I f you want a high- res olution vers ion, download the larger
images and us e them, like s o:

getSnaps.pl -big fubuki_macro


makeCollage.pl -big fubuki_macro

T hes e c ommands will download the medium- s ized vers ions of


Fubuki's images and will produc e a nic e big c ollage without the
_t s uffix in the filename: collage.png.
See Also

[Hack #33]

[Hack #34]

[Hack #49]
Hack 44. Find the Dominant Color of an
Image

Flickr doesn't have a color search f eature, but that shouldn't


stop you f rom building one!

T here are a lot of c ool things you c an do if you know the


dominant c olors of a group of images . For ins tanc e, you c an
make us er interfac es for s earc hing large quantities of photos by
c olor, s uc h as the Flic kr C olr P ic kr [Hack #45], and you c an
c reate fas c inating c ollages by arranging the photos by
luminanc e, s aturation, or hue.

T he s imples t way I 've found to find the dominant c olor of an


image is to res ize the image to 1 x 1 (produc ing a s ingle pixel)
and then rec ord the c olor of that pixel. T his will produc e a value
that is (or is c los e to, depending on the res izing algorithm) the
average c olor of the image.

T his hac k provides two s c ripts : s amplePhoto.pl s amples a s ingle


photo, and s ampleSnaps .pl s amples a large c ollec tion of photos
(thumbnails , hopefully) and s aves the information in a file that
c an be read by other s c ripts .

What You Need

To run the s c ripts in this hac k, you'll need the following two
modules :

Image::Magick

T his P erl module provides an A P I for the powerful


I mageM agic k image- proc es s ing library. You c an find it
at http://www.imagemagic k.org, or you c an download it
from C P A N .

For Windows , the P erl module c omes with


the lates t ins taller from the I mageM agic k
s ite; however, you might have problems
getting this vers ion to ins tall properly,
depending on your P erl c onfiguration. I f,
after ins talling I mageM agic k, you have
problems with the A c tiveState vers ion of
P erl, us e ppm to ins tall the P erl module, by
is s uing the following c ommand:

ppm install Image-Magick ppd

Data::Dumper

T he s c ripts in this hac k produc e output in the form of a


text file that c an be pars ed by other P erl s c ripts . A n
eas y way to ac c omplis h this is to build up the data
s truc ture in P erl and then us e Data::Dumper to dump it
into a text file.

The Code

H ere's a bas ic s c ript that outputs c olor information for a s ingle


photo, in H T M L format, us ing the Image::Magick module. C reate a
file c alled s amplePhoto.pl and enter the following c ode:

#!/usr/bin/perl -s

#
# samplePhoto.pl - Jim Bumgardner
#

use Image::Magick;

$Data::Dumper::Terse = 1; # avoids $VAR1 = * ; in dumper output


$Data::Dumper::Indent = $verbose? 1 : 0; # more concise output

$photoname = shift;
die "samplePhoto.pl <photoname>\n" if !$photoname;

my $image = Image::Magick->new;
$err = $image->Read($photoname);
die $err if $err;
my ($w,$h) = $image->Get('width','height');
$image->Resize(geometry=>'1x1');
($r,$g,$b) = $image->GetPixels(x=>0,y=>0,width=>1,height=>1,normal
undef $image;
$colorspec = sprintf "#%02x%02x%02x", $r, $g, $b;
$textcolor = $g < 128? 'white' : 'black';

print <<EOT;

<html><body>
<table><tr>
<td><img src="$photoname" /></td>
</tr><tr>
<td bgcolor=$colorspec>
<font color=$textcolor>
R: $r<br>
G: $g<br>
B: $b<br>
</font>
</td></tr></table>
</body></html>

EOT
# end of script

T he s ec ond s c ript rec ords c olor information for a large c ollec tion
of photos , us ing a photo lis t c reated by the getP hotoL is t.pl
s c ript [Hack #33] . Save this s c ript as s ampleSnaps .pl:

#!/usr/bin/perl -s

#
# sampleSnaps.pl - Jim Bumgardner
#

use Image::Magick;
use Data::Dumper;
$Data::Dumper::Terse = 1; # avoids $VAR1 = * ; in dumper output
$Data::Dumper::Indent = $verbose? 1 : 0; # more concise output

$photolist = shift;
$dirname = shift;
die "sampleSnaps.pl <photolist_file> [dirname]\n" if !$photolist;

$dirname = $photolist if !$dirname;


$dirname =~ s/\.ph// if $dirname =~ /\.ph$/;
$photolist .= '.ph' if !($photolist =~ /\./);

require "$photolist";

$n = scalar(@photos); # count photos


print "$n photos in file\n";

@sampledPhotos = ( );

$nbrSampled = 0;

$firstPhoto = $photos[0];
$suffix = '_t' if !$suffix;

foreach $photo (@photos)


{
my ($owner, $secret, $server) = ($photo->{owner},$photo->{secret
$fnam = "$dirname/$photo->{id}$suffix.jpg";

my $image = Image::Magick->new;
$err = $image->Read($fnam);
if ("$err") {
warn "$err";
next;
}
($w,$h) = $image->Get('width','height');
$x = $image->Resize(geometry=>'1x1');

($r,$g,$b) = $image->GetPixels(x=>0,y=>0,width=>1,height=>1,norm
undef $image;

($photo->{r},$photo->{g},$photo->{b}) = ($r,$g,$b);

++$nbrSampled;
print "$nbrSampled...\n" if $nbrSampled % 50 == 0;
}

$ofname = "$dirname/samples.ph";

open (OFILE, ">$ofname");


print OFILE "\@photos = (\n";
$n = 0;
foreach $photo (@photos)
{
print OFILE ($n++? ",\n" : "") . Dumper($photo);
}
print OFILE "\n);\n1;\n";
close OFILE;

print "$nbrSampled sampled to $ofname\n";

Running the Hack

To us e the s amplePhoto.pl s c ript, you'll need a photo to work on.


H ere's a s ample run us ing a J P E G file of a watermelon:

samplePhoto.pl watermelon.jpg >test.html


You c an view the file tes t.html in a web brows er to s ee the res ult,
as s hown in Figure 7 - 2 .

Figure 7-2. Output of samplePhoto.pl


You'll find that the c olor values produc ed us ing this method tend
to be more s ubdued than the c olors in the ac tual images . T his is
bec aus e the tec hnique is averaging c olor values . I f you average
two bright c olors that have oppos ite hues , you will end up with a
s ubdued gray c olor. I n the image in Figure 7 - 2 , the green c olor of
the watermelon rind and bac kground help to neutralize the vivid
c olor of the watermelon fles h.

I nteres tingly, I 've found that if you take a large c ollec tion of
digital photographs from Flic kr and average the c olors together,
it tends to produc e a dull brown or orange c olor, rather than gray,
as you might expec t. Why this is s o, I 'm not s ure. Some s ay it
has s omething to do with the qualities of indoor lighting and flas h
photography. C omputer graphic s guru Kevin Bjorke offers a more
pros aic explanation: "I t's the c olor of dirt and people."

To us e the s ampleSnaps .pl s c ript, whic h s amples a large group of


images , you'll need the s c ripts developed in [H ac k #3 3 ] and
[Hack #34] . H ere's how to download and c olor- s ample a s et of
images of aardvarks :

getPhotoList.pl aardvark
getSnaps.pl aardvark
sampleSnaps.pl aardvark

T he firs t c ommand us es the Flic kr A P I to produc e a lis t of


relevant photos , whic h are s aved in aardvark.ph. T he s ec ond
c ommand downloads thumbnails of eac h of thes e images into the
direc tory aardvark. T he final c ommand s amples the c olors of all
the photos and s aves the photo and c olor information into a file
c alled aardvark/s amples .ph. T his file c ontains the s ame data that
is in aardvark.ph but adds r, g, b, and l fields , whic h repres ent
red, green, blue, and luminanc e, res pec tively. H ere's an exc erpt:

@photos = (

{'owner' => '24512271@N00','isfriend' => '0','r' => '0.49369040131


'secret' => '4551f2bed3', 'b' => '0.44110780954361','g' => '0.4470
'title' => 'Groupportrait','server' => '3','id' => '5024662','isfa

{'owner' => '66208233@N00','isfriend' => '0','r' => '0.51206225156


'secret' => 'fef397ccee', 'b' => '0.466559857130051','g' => '0.491
'title' => 'Grooming is important','server' => '8','id' => '119990

{'owner' => '44124388719@N01','isfriend' => '1','r' => '0.60651558


'title' => 'The Night Visitor','server' => '4','id' => '5043567','

# etc...

We'll us e this data in [Hack #45] to build an interfac e that


quic kly s earc hes and returns photos that matc h a s pec ific c olor.

Hacking the Hack

T he c olor values in thes e s c ripts are normalized c olor values ,


whic h are floating- point numbers that go from 0 to 1 . You might
prefer the more c onc is e 8 - bit integer repres entation, in whic h
eac h c olor c omponent is a number from 0 - 2 5 5 . You c an c onvert
the normalized c olors to 8 - bit integers by adding this c ode to
the s c ript:
# Convert normalized RGB values to 8-bit integers:
$r = int($r*255);
$g = int($g*255);
$b = int($b*255);
($photo->{r},$photo->{g},$photo->{b)) = ($r,$g,$b);

T he three values that we are s o interes ted in r, g, and brepres ent


the res pec tive red, green, and blue c olor c omponents of the
pixel. But there are a variety of ways to analyze c olor, as ide from
boring old RG B. I f you are interes ted in ans wering ques tions
s uc h as "H ow bright is the photo? " or "H ow c olorful is the
photo? ," the RG B values are not nec es s arily ideal.

O ther c olor s pac es inc lude C M Y K (c yan, magenta, yellow, and


blac k), c ommonly us ed in the print indus try, and H SV (hue,
s aturation, and value; s ometimes c alled H SB for hue, s aturation,
and brightnes s ). T he H SV c olor s pac e is partic ularly us eful for
evaluating c olor in a more artis tic and intuitive way. For
example, if the s aturation value (s) is high, you know the image
is colorful. I f the brightnes s value (v) is high, you know the image
is bright. I f you s ort the images from left to right to c orres pond
to their hue values (h), it produc es a rainbow pattern.

I us e the following P erl func tion to c onvert from RG B to H SV


values :

sub RGBtoHSV($$$)
{
my ($r,$g,$b) = @_;
my $max = $r > $g? $r : $g;
$max = $max > $b? $max : $b;
my $min = $r < $g? $r : $g;
$min = $min < $b? $min : $b;
my $v = $max;
my $s = ($max != 0)? ($max-$min)/$max : 0;
my $h;
if ($s == 0) {
$h = 0; # undefined, actually
}
else {
my $d = $max - $min;
if ($r == $max) {
$h = ($g - $b)/$d;
}
elsif ($g == $max) {
$h = 2 + ($b-$r)/$d;
}
elsif ($b == $max) {
$h = 4 + ($r-$g)/$d;
}
$h *= 60;
if ($h < 0) {
$h += 360;
}
}
return ($h,$s,$v);
}

To inc orporate this into the s ampleSnaps .pl s c ript, add the
func tion to the bottom of the s c ript. T hen, after the line that
generates the RG B values :

($r,$g,$b) = $image->GetPixels(x=>0,y=>0,width=>1,height=>1,norm
you c an c onvert them to H SV values :

($h,$s,$v) = RGBtoHSV($r,$g,$b);

A nother us eful quality to look for is luminance, whic h is a


meas ure of how bright the c olor appears to the human eye. T here
are a few ways to meas ure luminanc e. T he v value returned by
the RGBtoHSV() c omes pretty c los e, but it does n't take into
ac c ount the apparent differenc es in the brightnes s of hues ; for
example, pure green appears brighter to the eye than pure blue.
A good RG B- to- luminanc e formula that I often us e is H aeberli's
luminanc e equation:

$lum = 0.3086*$r + 0.6094*$g + 0.0820*$b; # Haeberli's luminan

I n my own s c ripts , I us ually don't bother s toring either the H SV


values or the luminanc e values , s inc e I c an eas ily c onvert the
RG B values to H SV or luminanc e on the fly when I need them,
us ing the tec hniques in this hac k.

For an exc ellent introduc tion to c olor s pec ific ation and image
c oding, c hec k out the C olor FA Q :

http://www.poynton.c om/notes /c olour_and_gamma/C olorFA

See Also

[Hack #33]
[Hack #34]

[Hack #43]

[Hack #49]
Hack 45. Make a Color Picker

This colorf ul interf ace is f un to use and f unctional.

T he Flic kr C olr P ic kr (http://www.krazydad.c om/c olrpic kr/) was


one of the firs t Flic kr- powered applic ations I built, and it has
been the ins piration for a lot of my other Flic kr- related work. T he
bas ic idea was to c ombine an H SV c olor pic ker, a c ommon
feature in many paint and illus tration programs , with a photo
brows er. When you c lic k on a c olor on the c olor wheel, a group of
thumbnail images that matc h the c olor pops up nearly
ins tantaneous ly.

M os t us ers quic kly gras p the bas ic c onc ept of "point at a c olor,
s ee pretty pic tures " and have a lot of fun playing with it. M any
artis ts and des igners have told me they find this a us eful
interfac e for s earc hing for photos that matc h a partic ular palette.

P eople often as s ume that this interfac e makes us e of a c olor-


s earc h c apability built into Flic kr, but alas , Flic kr offers no s uc h
s ervic e (yet). To make a c olor pic ker, you mus t firs t prec ompute
the average c olors of the photos you wis h to s earc h. T his is
done us ing the P erl s c ript developed in [Hack #44] . H ere, we'll
us e a new P erl s c ript to c onvert that information to an
A c tionSc ript text file, whic h we c an then inc lude in a Flas h
movie. T he H SV c olor pic ker interfac e is c reated us ing Flas h
A c tionSc ript.
What You Need

T his hac k us es the modular P erl s c ripts developed in [H ac k


#3 3 ], [H ac k #3 4 ], and [Hack #44] . T he Flas h template us ed in
this hac k requires M ac romedia Flas h M X or a later vers ion.

To view the c olor pic ker, you'll need a web brows er with a Flas h
plug- in c apable of dis playing Flas h 6 movies or later.

T he s c ripts and the Flas h template are all available in a s ingle


arc hive, whic h you c an download here:

http://www.krazydad.c om/s ware/J ims Flic krSc ripts .zip

The Code

T his P erl s c ript is res pons ible for c onverting image data from
P erl s yntax into A c tionSc ript s yntax, s o we c an inc lude the data
in a Flas h movie.

T his s c ript is inc luded in the c ollec tion of


P erl s c ripts in the Jims FlickrScripts .zip
arc hive mentioned in the previous s ec tion.

C reate a new text file c alled makeFlas hDB.pl and enter the
following P erl c ode:
#!/usr/bin/perl -s
#
# Convert Perl Photo List to Flash/ActionScript list for use in Co
# - Jim Bumgardner
#
$photolist = shift;
$dirname = shift;
$dirname = $photolist if !$dirname;
$dirname =~ s/\.ph// if $dirname =~ /\.ph$/;
$ifname = "$dirname/samples.ph";

die "makeFlashDB.pl <photolist_file> [<dirname>]\n" if !$photolist


die "Photos have not yet been sampled with sampleSnaps.pl\n" if !(

require "$ifname";

$poolname = $dirname;

open (OFILE, ">$poolname.as");


print OFILE "poolname='$poolname';\n";
print OFILE "imgdb = [\n";

$n = 0;
foreach $photo (@photos)
{
print OFILE ",\n" if $n;
printf OFILE "{r:%d,g:%d,b:%d,owner:'%s', secret:'%s', server:%d
int($photo->{r}*255.999), int($photo->{g}*255.999), int($
$photo->{owner}, $photo->{secret},$photo->{server}, $phot
++$n;
}
print OFILE "\n];\n";

close OFILE;
Running the Hack

A c olor pic ker c an be made for any c ollec tion of photos on Flic kr,
but it works bes t if the c ollec tion has more than 5 0 0 photos .
H owever, you will als o enc ounter performanc e problems if the
number of photos exc eeds 2 0 ,0 0 0 or s o. T he more photos there
are in the databas e, the longer it will take to identify photos by
c olor and to load the Flas h movie.

T his hac k will make a c olor pic ker us ing the photos in the Stoc k
Repos itory group pool at http://www.flic kr.c om/groups /s toc k/. A t
las t c ount, this group had 1 ,6 5 8 photos in the pool, whic h is a
good number for a c olor pic ker.

Start by identifying the group's Flic kr group I D . You c an do this


us ing a Flic kr A P I c all, s uc h as flickr.groups.pools.getGroups,
but there is a fas ter way. I n your web brows er, examine the U RL
of the group's image ic on (by viewing its properties ):

http://static.flickr.com/1/buddyicons/49503068103@N01.jpg?10915605

T he group I D is the part of the ic on filename that prec edes the


.j pg extens ionin this c as e, 49503068103@N01.

N ext, download information about eac h of the photos in the


group, us ing the s c ript developed in [Hack #33] :

> getPhotoList.pl -g 49503068103@N01


Searching for photos in group 49503068103@N01
Page 1 of 4
Page 2 of 4
Page 3 of 4
Page 4 of 4
1658 photos written to 49503068103@N01.ph

T hen, rename the res ulting file to make it a little eas ier on the
eyes :

> mv 49503068103@N01.ph stock.ph

You now have a file c alled s tock.ph, whic h c ontains a des c ription
of eac h photo in the Stoc k Repos itory pool.

N ext, download a thumbnail image for eac h photo in the group,


us ing the s c ript developed in [Hack #34] . T his will c reate a
direc tory c alled s tock/, whic h will c ontain all the thumbnail
images :

> getSnaps.pl stock.ph

Adding stock/48828925_t.jpg...
Adding stock/20569503_t.jpg...
Adding stock/30148198_t.jpg...
Adding stock/24745811_t.jpg...
Adding stock/56897033_t.jpg...
Adding stock/40633875_t.jpg...
Adding stock/51200366_t.jpg...
Adding stock/26152510_t.jpg...
[etc...]
1610 added

N ow it's time to s ample the c olors , us ing the s c ript developed in


[Hack #44] . T his will c reate a file c alled s tock/s amples .ph, whic h
c ontains the c olor information:

> sampleSnaps.pl stock.ph

1658 photos in file


50...
100...
150...
200...
250...
[etc...]
1658 sampled to stock/samples.ph

You now mus t us e the s c ript you jus t c reated, makeFlas hDB.pl, to
c onvert the information in s tock/s amples .ph (whic h is in P erl
s yntax) to a file with A c tionSc ript s yntax (s tock.as ), whic h you'll
be able to us e in the Flas h movie:

> makeFlashDB.pl stock

I f you look at the res ulting s tock.as file, you'll s ee an


A c tionSc ript table that looks like this :

poolname='stock';
imgdb = [
{r:179,g:170,b:104,owner:'74112673@N00', secret:'f0d1bae053', serv
{r:70,g:55,b:52,owner:'73624728@N00', secret:'ffb2f98e7d', server:
{r:131,g:129,b:109,owner:'46172547@N00', secret:'a396cdca40', serv
{r:139,g:137,b:135,owner:'86497205@N00', secret:'44607ffa2d', serv
[etc...]

You're almos t ready to us e the Flas h template. C opy the Flas h


template provided in Jims FlickrScripts .zip to a new Flas h projec t
file:

> mv colrpickr_template.fla stockPickr.fla

T hen, open the new template, s tockPickr.fla, in the Flas h


authoring environment. You'll s ee that the movie has two frames
in the timeline. T he firs t frame inc ludes a s c ript that c ontains
the bulk of the c ode for the c olor pic ker:

// Colr Pickr Template - by Jim Bumgardner


#include "colrpickr.as"

You don't need to modify this s c ript.

T he s ec ond frame inc ludes a s c ript that is s uppos ed to c ontain


the image databas e:

#include "myphotolist.as"
doPick( );

M odify this line:

#include "myphotolist.as"

to read like this , s ubs tituting the name of the A c tionSc ript
databas e file you jus t c reated:

#include "stock.as"

T he c olor pic ker is now ready to be tes ted.

You c an us e the C ontrol/P lay c ommand to tes t the movie within


the Flas h authoring environment. T he res ulting c olor pic ker
looks like Figure 7 - 3 .

Figure 7-3. A Flickr color picker


C lic k on the c olor wheel (or manipulate the light/dark s lider) to
view photos that matc h a partic ular c olor. C lic k on any photo to
be trans ported to its web page on Flic kr.

I f you like the res ults , s elec t the P ublis h c ommand on the File
menu to c reate a Flas h movie file. T his will c reate two files ,
s tockPickr.s wf and s tockPickr.html, whic h you c an upload to your
own web s erver.

Hacking the Hack

A lthough not printed in this book, the c ode for the c olor pic ker
interfac e is c ontained within colrpickr.as and is inc luded in the
Jims FlickrScripts .zip arc hive.

T he A c tionSc ript c ode draws the H SV c olor- wheel interfac e,


whic h allows the us er to s elec t an H SV c olor. T his c olor is
c onverted from H SV to RG B, and the 1 2 photos c los es t to the
RG B value are s elec ted (from the lis t of photos we embedded).
T he s c ript then downloads thumbnails for the photos from Flic kr
and dis plays them.

Sinc e the lis t of photos is embedded within the Flas h movie


its elf, there is a limit to how many photos c an be s earc hed this
way. T he s c ript works bes t with no more than a few thous and
photos . T he more photos you add, the bigger the Flas h movie
gets and the longer it takes to s earc h through them.

I n addition to working with Flic kr, the c ode is des igned s uc h that
it c an eas ily be modified to work with other web- bas ed image-
arc hiving s ervic es .

T he two key routines that you will need to modify to work with
other s ervic es are GetThumbUrl(), whic h c reates a U RL to a
thumbnail image, and GetExternalUrl(), whic h c reates a U RL to
the s ite where the image is hos ted. T hes e routines eac h rec eive
a s ingle argument, whic h is a rec ord c orres ponding to the photo:

// These two routines can be modified to make the colr pickr work
// with other image archives...

GetThumbUrl = function(imgRec)
{
return 'http://static.flickr.com/' +
imgRec.server + '/' + imgRec.id + '_' + imgRec.secret + '_
}

GetExternalUrl = function(imgRec)
{
return 'http://www.flickr.com/photos/' + imgRec.owner +
'/' + imgRec.id;
}

T he only important fields in the image rec ords that are us ed by


the remainder of the program are the r, g, and b fields , whic h
identify the c olor of eac h image in 8 - bit RG B s pac e. You c an add
any additional fields you like to thes e rec ords in order to
formulate U RL s .

O nc e you gras p the es s entials of this interfac e, you might want


to try extending it. H ow about adding the ability to s earc h for
photos that matc h two or three c olors , or a s erver- powered c olor
s earc h c apability? T hes e features will greatly inc reas e the
power and utility of this playful interfac e.

See Also

[Hack #33]

[Hack #34]

[Hack #44]
Hack 46. Make a Motivational Poster and
Other Swag

Create your own movie posters, magazine covers, and trading


cards in seconds.

FD 's Flic kr Toys (http://www.flagrantdis regard.c om/flic kr/) are a


great c ollec tion of online apps that will c onvert your Flic kr
photographs into all kinds of c ool s tuff, s uc h as movie pos ters
and magazine c overs .

Flickr Toys

FD , who goes by the name J ohn Wats on in real life, c urrently


offers 1 4 toys , with new ones on the way. T he c urrent lis t
features the following:

Badge Maker

FD 's firs t toy to ac hieve wide popularity allows you to


make your own unoffic ial Flic kr I D badge, s uitable for
laminating, as s hown in Figure 7 - 4 . T his has bec ome a
popular meme on Flic kr, and it's a good way to identify
yours elf in public to other Flic krites . D on't be s een
without your badge.
Figure 7-4. A Flickr badge
Billboard

P ut your photo on a freeway billboard, or at leas t on a


photo of a freeway billboard.

Calendar

Feature your photo in a monthly c alendar, s uitable for


hanging in the garage or planning important events , s uc h
as c leaning the garage.

Flickr Uploadr

U pload your photos to Flic kr us ing a Konfabulator widget


(this is a different widget than the one dis c us s ed in
[Hack #5]). Konfabulator, available at
http://www.konfabulator.c om, is a c ool tool for filling your
des ktop with gadgets and gewgaws .

Fortune

V iew a random photo, ac c ompanied by a random fortune,


pithy s aying, or as trologic al predic tionthe bes t random
orac le s inc e the I C hing!
Framer

P ut your photo into one of 1 9 unique frames that


trans form it into s omething els e. A vailable frames
inc lude realis tic - looking pos tage s tamps , c omplete with
pos tmarks (as s hown in Figure 7 - 5 ); autumn leaves ;
3 5 mm film; and P olaroids .

Figure 7-5. A stamp made with Framer


Magazine Cover

I nc orporate your photo into a s lic k- looking magazine


c over, with s uitable s tory titles , as s hown in Figure 7 - 6 .
C hoos e from s everal different des igns .

Figure 7-6. A magazine cover


Mos aic Maker

H ere's yet another method to put a handful of photos


into c olumns and rows . For more methods , s ee [Hack
#32] .

Motivator

M ake a motivating (or unmotivating) pos ter, s uitable for


pic king up the s pirits of your c oworkers (or pos s ibly
trampling up and down on thos e s ame s pirits ). See the
following s ec tion for an example.

Movie Pos ter

M ake an attrac tive lobby c ard with title, taglines ,


releas e date, and c redits , jus t like Figure 7 - 7 .

Figure 7-7. A movie poster


On Black

M ake a permanent web page dis playing your photo on a


lovely all- blac k (or all- white) bac kgrounda helpful tool
for thos e making web galleries .

Random Photo Brows er

Brows e a s elec tion of random photos , eac h of whic h was


made a favorite by at leas t one pers ona c haotic
as s ortment of the c rème de la c rème.

Slides how

C reate a (J avaSc ript) s lides how from a group of your


photos . Slides hows are hos ted on FD 's web s ite. (For
another method of making s lides hows , s ee [Hack #50] .)

Trading Card Maker

M ake a trading c ard, in the s tyle of P okemon or M agic ,


as s hown in Figure 7 - 8 . C reate c us tom c ards for your
own c us tomized role- playing games .

Figure 7-8. A trading card


M os t of thes e toys us e a Flic kr photograph as s ourc e material
and then add text, graphic overlays , and other elements to
produc e an authentic - looking res ult. T he great thing about thes e
toys is that FD has exc ellent des ign s kills , s o his s c ripts
amount to free graphic des ign jobs from a profes s ional.

M any of the toys produc e images that make great gifts for
birthdays , retirement parties , and other oc c as ions that c all for
s omething a little s pec ial.

We'll us e the M otivator as an example here to s how how the toys


work. Fill out a few fields in a form, and it will produc e a s uitably
ins piring (or pretentious - looking) motivational pos ter.

Creating an Unmotivational Poster

To s ee how FD 's toys work, we'll make an unmotivational pos ter.


Firs t, go to your Flic kr photos tream and find a photo you like.
C opy the U RL of the page from your brows er's addres s bar. For
our example, we'll us e the photo found at
http://www.flic kr.c om/photos /krazydad/6 0 1 4 5 4 2 1 /.

T hen, go to FD 's Flic kr Toys s ite


(http://www.flagrantdis regard.c om/flic kr/) and c lic k the
M otivator link. You'll be pres ented with the form s hown in Figure
7 -9 .

Figure 7-9. FD's Motivator


P as te in the addres s of your photo, and then enter a title and
s ome motivational text for your pos ter.

When you pres s the M otivate button, FD 's s c ript will do s ome
proc es s ing and then produc e an attrac tive and ins piring res ult
like the one s hown in Figure 7 - 1 0 .

Figure 7-10. An unmotivational poster


Rolling Your Own

I f you're interes ted in making your own toy, you're in luc k! FD


has kindly provided s ome P H P s ourc e c ode that reproduc es the
M otivator s c ript but us es a s tripped- down form. T his is an
exc ellent s tarting point for making other P H P tools that tweak
Flic kr photos .

Before rolling your own, be s ure to c hec k


out FD 's s ite! Sinc e this was written, he
has probably added a few more Flic kr Toys
to the c ollec tion.

The code

C reate a file c alled motivator.php and enter the following c ode:

<?php
// Configuration stuff
$flickrAPIKey = "<your_api_key>";
require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey);

// Fonts to use on the poster


$font1 = "times";
$font2 = "verdana";

// Get input variables and defaults


$url = '';
$title = '';
$text = '';
$color = "ffffff";
if (isset($_GET['url'])) $url = $_GET['url'];
if (isset($_GET['title'])) $title = $_GET['title'];
if (isset($_GET['text'])) $text = $_GET['text'];
if (isset($_GET['color'])) $color = $_GET['color'];

if (isset($_GET['button'])) {
// Create a 750x600-pixel canvas, on which we'll draw everythi
$canvas = imagecreatetruecolor(750, 600);

// Fill the canvas with a black background


imagefill($canvas, 0, 0, hexdec("#000000"));

// Add a border by drawing a colored rectangle


// and then a black rectangle inside of that
imagefilledrectangle($canvas, 70, 45, 679, 454, hexdec($color)
imagefilledrectangle($canvas, 72, 47, 677, 452, hexdec("#00000

// Get the Large (_b) version (or the Original


// (_o) size if Large isn't available)
$jpg = null;
$info = array( );
if (preg_match('!http://.*?/photos/.*?/(\d+)!i', $url, $match)
$id = $match[1];
$info = $f->photos_getInfo($id);
$sizes = $f->photos_getSizes($id);
foreach($sizes as $size => $sizedata) {
if ($size == "Large" || $size == "Original") {
$source = $sizedata['source'];
if (preg_match('/\.(jpg|jpeg)$/i', $source)) {
$jpg = imagecreatefromjpeg($source);
}
if (preg_match('/\.png$/i', $source)) {
$jpg = imagecreatefrompng($source);
}
if (preg_match('/\.gif$/i', $source)) {
$jpg = imagecreatefromgif($source);
}
break;
}
}

// Center the image on the canvas


imagecopy($canvas, $jpg, 75, 50, (imagesx($jpg)-600)/2, (i

// Draw the title text


// imagettfbbox( ) is a function that returns the
// coordinates of a box that would contain the text to be
// The output of that function is used to determine how
// to center the image on the canvas.
$title = strtoupper(join(preg_split('//', $title), ' '));
$bbox = imagettfbbox(56, 0, $font1, $title);
$x = (imagesx($canvas) - $bbox[2])/2; // x-coordinate to c
$y = abs($bbox[7]-$bbox[1])+465; // y-coordinate
imagettftext($canvas, 56, 0, $x, $y, hexdec($color), $font

// Draw the motivational text


$bbox = imagettfbbox(16, 0, $font2, $text);
$x = (imagesx($canvas) - $bbox[2])/2; // x-coordinate to c
imagettftext($canvas, 16, 0, $x, $y+30, hexdec("#ffffff"),

// Save a copy of the image


imagejpeg($canvas, "motivator.jpg", 90);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "ht
<html>
<head>
<title>Motivator</title>
</head>
<body>
<form action="motivator.php" method="get">
Url: <input name="url">
Title: <input name="title">
Text: <input name="text">
Color: <input name="color"> (Use HTML color codes, e.g
<input type="submit" name="button" value="Create">
</form>
<?php if (isset($_GET['button'])) { ?>
<img src="motivator.jpg?v=<?php echo rand(1,1000000) ?>" a
<?php } ?>
</body>
</html>

Running the Hack

You will need to edit the firs t line at the top of the file, replac ing
<your_api_key> with your ac tual A P I key. T hen, upload the s c ript
to your web s erver.

T he c ode is written to us e the T imes and Verdana truetype fonts .


You c an either upload the C:\WI NNT\Fonts \times .ttf and
C:\WI NNT\Fonts \verdana.ttf files from a Windows mac hine, or
modify the c ode to us e different fonts (and upload thos e).

You'll als o need write permis s ions s o that


the s c ript c an c reate the file motivator.j pg.

M os t of FD 's tools are P H P s c ripts that us e the G D graphic s


library. T he I mageM agic k library (http://www.imagemagic k.org)
is als o a good c hoic e for this kind of work and is perhaps a bit
more powerful than G D , but many hos ting providers provide G D
as a built- in part of their P H P ins tallations , whereas
I mageM agic k c an be harder to find.

See Also

[Hack #43]

[Hack #47]
[Hack #50]
Hack 47. Make a Ransom Note

Say it with photos, and def y handwriting analysts everywhere!

I n thes e unc ertain days of paperles s offic es and ins tant


mes s aging, it c an be diffic ult for harried kidnappers to find
magazines , news papers , s c is s ors , and glue. So, it's good to
know that high- tec h kidnappers c an us e their s tolen laptops to
make good old- fas hioned rans om notes with Flic kr!

Flic kr c ontains a few groups that c ollec t photos of individual


c harac ters or glyphs . T he firs t s uc h group was O ne L etter
(http://www.flic kr.c om/groups /oneletter/), whic h c ollec ts photos
of the letters A through Z. T his was followed by O ne D igit
(http://www.flic kr.c om/groups /onedigit/), whic h c ollec ts photos of
the digits 0 through 9 . A nd then c ame P unc tuation
(http://www.flic kr.c om/groups /punc tuation/), whic h c ollec ts
photos of, uh, punc tuationyou know, the s tuff that c artoon
c harac ters us e to c urs e with.

T he P H P s c ript in this hac k trans lates a s tring of A SC I I text


into a s equenc e of photos from thes e groups , produc ing a
types etting job only a felon c ould love.

I n [Hack #13], we looked at the O ne Word


group
(http://www.flic kr.c om/groups /oneword/),
whic h c ontains photos of individual words .
You c an build a rans om note out of whole
words us ing the tec hniques in this hac k,
but here we'll build our words one letter at
a time.

What You'll Need

To us e this P H P s c ript, you'll need a web s erver that s upports


P H P 4 or later and your own Flic kr A P I key. See [Hack #40] for
information on how to get an A P I key.

You'll als o need the phpFlic kr s c ripts [Hack #41] . (T hes e


s c ripts als o make authentic ating other people a s nap, but you
won't need authentic ation for this hac k.) You c an download thes e
s c ripts from http://www.phpflic kr.c om.

The Code

C reate a file c alled rans omNote.php and add the following c ode:

<?php

// Ransom Note - Jim Bumgardner


//
// Pulls glyphs from One Letter, One Digit, and Punctuation groups
//
ini_set("error_reporting ", E_ALL);

// Configuration stuff
$flickrAPIKey = "your API key";
$cachingenabled = true;
$dbUser = "user"; //database user here
$dbPass = "pass"; //database password here
$dbAddress = "localhost"; //location of database
$dbName = "dbName"; //name of database, will create one if it does

// Create new phpFlickr object


require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey);
if ($cachingenabled == true)
{
$f->enableCache("db", "mysql://$dbUser:$dbPass@$dbAddress/$dbNam
}

// Exceptional tags - all others are the letter or digit.


$exTags = array(
'a' => 'aa',
'i' => 'ii',
'0' => '00',
'%' => 'percent',
'+' => 'plussign',
'.' => 'period',
',' => 'comma',
'$' => 'dollarsign',
'!' => 'exclamationpoint',
'?' => 'questionmark',
';' => 'semi colon',
':' => 'colon',
'/' => 'slash',
'-' => 'dash',
'&' => 'ampersand',
'>' => 'greaterthan',
'<' => 'lessthan');

$oneLetterGroup = '27034531@N00'; // group_id of 'One Letter'


$oneDigitGroup = '54718308@N00'; // group_id of 'One Digit'
$punctuationGroup = '34231816@N00'; // group_id of 'Punctuation'

$phrase = 'pay-up or else!';


if (isset($_GET['phrase']))
$phrase = $_GET['phrase'];

$size = 'thumbnail';
if (isset($_GET['size']))
$size = $_GET['size'];

$len = strlen($phrase);
$ltrphotos = array( );

for ($i = 0; $i < $len; ++$i)


{
$char = strtolower(substr($phrase,$i,1));
if ($char == ' ')
continue;
// Get photo list for unique letters
if (!isset($ltrphotos[$char]))
{
if (isset($exTags[$char]))
$tag = $exTags[$char];
else
$tag = $char;

if ($char >= 'a' && $char <= 'z')


$group_id = $oneLetterGroup;
else if ($char >= '0' && $char <= '9')
$group_id = $oneDigitGroup;
else
$group_id = $punctuationGroup;
$photos = $f->groups_pools_getPhotos($group_id,$tag);
$ltrphotos[$char] = $photos;
}
}

function buildPhotoSourceURL ($photo)


{
return "http://www.flickr.com/photos/" .
$photo['owner'] . "/" . $photo['id'] . "/";
}

?>

<html>
<head>
<title>ransom note</title>
</head>
<body>
<center>

<?php

for ($i = 0; $i < $len; ++$i)


{
$char = strtolower(substr($phrase,$i,1));
if ($char == ' ')
echo "<br>\n";
else {
$photoIdx = array_rand($ltrphotos[$char]['photo']);
$photo = $ltrphotos[$char]['photo'][$photoIdx];
echo "<a href=" .
buildPhotoSourceURL($photo) .
"><img border='0' alt='$photo[title]' src=".
$f->buildPhotoURL($photo, $size) . "></a>";
}
}

?>

</center>
</body>
</html>

Before uploading the s c ript, edit the following line to us e your


own A P I key:

$flickrAPIKey = "your API key";

T he phpFlickr wrapper has an optional c ac hing feature. I f you


wis h to us e it, modify thes e lines to provide ac c es s information
for a databas e on your s erver:

$cachingenabled = true;
$dbUser = "user"; //database user here
$dbPass = "pass"; //database password here
$dbAddress = "localhost"; //location of database
$dbName = "dbName"; //name of database, will create one if it does
I f you do not wis h to us e c ac hing, turn it off by replac ing this
line:

$cachingenabled = true;

with this :

$cachingenabled = false;

Running the Hack

To run the hac k, upload the edited s c ript to your web s erver, and
invoke it by typing the U RL in your brows er's addres s bar:

http://www.yourdomain.com/ransomNote.php

You'll s ee a rans om note appear, like the one s hown in Figure 7 -


11.

Figure 7-11. Flickr ransom note


I f the default mes s age, "P ay- up or els e! ," is n't threatening
enough, you c an s pec ify a different mes s age by pas s ing the
variable phrase. H ere's an example:

http://www.yourdomain.com/ransomNote.php?phrase=I+love+kittens
You c an als o s pec ify different photo s izes by us ing the size
parameter. H ere are the available c hoic es (from s malles t to
larges t):
square
thumbnail
small
medium
large
original

For example:

http://www.yourdomain.com/ransomNote.php?phrase=teensy+photos&size

Finally, if you want to s upport your fellow kidnappers , pleas e join


the O ne L etter, O ne D igit, and P unc tuation groups on Flic kr, and
c ontribute to thes e valuable photo pools ! With enough photos ,
we'll be able to types et longer works of literature than the one
s hown in Figure 7 - 1 2 .

Figure 7-12. Excerpt from "Jabberwocky" by


Lewis Carroll
See Also

[Hack #41]

[Hack #13]
Hack 48. Make a Slider Puzzle

Mix up your photos with this simple puzzle.

I n [Hack #50], we built a s imple applic ation in whic h a P H P


s c ript pas s ed parameters to a Flas h movie. T his hac k extends
that c onc ept by us ing a s lightly more c omplex Flas h movie that
breaks photographs apart into s eparate tiles to make a s lider
puzzle.

What You Need

T his hac k us es a modified vers ion of the s c ript developed in


[Hack #50], s o it might help if you look at that hac k firs t
(although it is n't s tric tly nec es s ary). Sinc e this hac k us es P H P,
you will need a web s erver with P H P s upport.

To view the res ults , you'll als o need a web brows er with a Flas h
plug- in c apable of dis playing Flas h 7 movies or later.

T he hac k us es a ready- made Flas h movie I developed c alled


Flic krP uzzle. Flic krP uzzle will make a puzzle from images from
any web s ite, not jus t Flic kr; however, it works bes t with 5 0 0 x
5 0 0 s quare images .

D ownload the arc hive from


http://www.krazydad.c om/flic krP uzzle/ and inc lude the
flas hPuzzle.s wf movie file in the direc tory where you are
developing your c us tomized vers ion of the puzzle.

You'll als o need the phpFlic kr s c ripts [Hack #41] . (T hes e


s c ripts als o make authentic ating other people a s nap, but you
won't need authentic ation for this hac k.) You c an download thes e
s c ripts from http://www.phpflic kr.c om.

The Flash Movie

FlickrPuzzle.s wf, the Flas h movie, ac c epts two parameters , whic h


c an be pas s ed in via H T M L :

imgUrl

T his is the full U RL of the image file to us e for the


puzzletypic ally, a J P G , G I F, or P N G . You c an us e images
from any s ourc e, not jus t Flic kr, but I rec ommend us ing
images that are 5 0 0 x 5 0 0 s quares , s uc h as mos t of the
images in the Squared C irc le group
(http://www.flic kr.c om/groups /c irc le/) on Flic kr. I f the
image does not have thes e dimens ions , it will be
s tretc hed to fit.

TD

T his is the horizontal (or vertic al) dimens ion of the


puzzle, in tiles . I f you s pec ify 5 (the default), the puzzle
will have 5 x 5 tiles . I rec ommend us ing the numbers 3,
4, or 5. I f you us e numbers larger than 5, the puzzle will
take longer to load, bec aus e Flas h mus t load duplic ate
c opies of the image for eac h tile in the puzzle.
U nfortunately, this is a limitation of Flas h. A t any rate,
puzzles with dimens ions of more than 5 x 5 tiles are not
muc h fun to s olve.

T hes e parameters are pas s ed in two s eparate loc ations within


the H T M L <object> tag that loads the Flas h movie, as you'll s ee
in the P H P s c ript below.

The Code

T he following P H P s c ript is res pons ible for loading random


images from Flic kr and then pas s ing the U RL of one of thos e
images to the Flas h movie that makes the puzzle. I t is a
modified vers ion of the s c ript developed in [Hack #50], whic h
us es s imilar tec hniques .

C reate a new text file c alled flickrPuzzle.php and enter the


following P H P c ode:

<?php
ini_set("error_reporting ", E_ALL);

// Configuration stuff
$flickrAPIKey = "your API key";
$cachingenabled = true;
$dbUser = "user"; //database user here
$dbPass = "pass"; //database password here
$dbAddress = "localhost"; //location of database
$dbName = "dbname"; //name of database, will create one if it does

function buildPhotoSourceURL ($photo)


{
return "http://www.flickr.com/photos/" .
$photo['owner'] . "/" . $photo['id'] . "/";
}

// Create new phpFlickr object


require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey);
if ($cachingenabled == true)
{
$f->enableCache("db","mysql://$dbUser:$dbPass@$dbAddress/$dbName
}

$per_page = 6;

// Parse parameters
$page = mt_rand(2,3700);
if (isset($_GET['page']))
$page = $_GET['page'];

$idx = mt_rand(1,$per_page);
if (isset($_GET['idx']))
$idx = $_GET['idx'];

$TD = 5;
if (isset($_GET['TD']))
$TD = $_GET['TD'];

$group_id = '52242140489@N01';
if (isset($_GET['group_id']))
$group_id = $_GET['group_id'];

$photos = $f->groups_pools_getPhotos($group_id,NULL,NULL,$per_page

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "ht
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-88
<title>Flickr Puzzle</title>
</head>
<body>
<center><table><tr>
<td valign=bottom width=100><a href="http://www.krazydad.com/flick
<?php
$i = 1;
foreach ($photos['photo'] as $photo) {
echo "<td align=center width=81><a href=http://www.krazydad.co
"&TD=$TD&page=$page><img border='0' width=75 height=75 al
$f->buildPhotoURL($photo, 'square') . "></a><br><a href="
buildPhotoSourceURL($photo) . ">flickr</a></td>";
if($i == $idx)
$imgUrl = $f->buildPhotoURL($photo, 'medium');
$i++;
}
print <<<EOT
<td valign=bottom width=100 align=right><a href="http://www.krazyd
<a href="http://www.krazydad.com/flickrPuzzle/index.php?idx=$idx&T
<a href="http://www.krazydad.com/flickrPuzzle/index.php?idx=$idx&T
</td></tr></table>

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"

codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/fla
width="500" height="500" id="flickrPuzzle" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flickrPuzzle.swf?imgUrl=$imgUrl&TD=$TD"
<param name="quality" value="high" />
<param name="bgcolor" value="#FFFFFF" />
<embed src="flickrPuzzle.swf?imgUrl=$imgUrl&TD=$TD"
quality="high" bgcolor="#FFFFFF" width="500" height="500" name="f
align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
EOT;
?>
</center>
</body>
</html>

You'll need to modify the c onfiguration information at the top,


providing your A P I key, s hared s ec ret, and databas e information
if you want c ac hing. For more information about this , s ee [Hack
#41] .

U pload this P H P file, flickrPuzzle.php, as well as the Flas h movie,


flickrPuzzle.s wf, to your web s erver.

Running the Hack

To run the hac k, enter the addres s of flickrPuzzle.php into your


web brows er's addres s bar:

http://www.yourdomain.com/flickrPuzzle.php

I f all goes well you'll s ee s omething like Figure 7 - 1 3 , a s et of


photograph tiles with one mis s ing.

Figure 7-13. flickrPuzzle


T his is a typic al s lider puzzle. You s olve it by c lic king on tiles
that are adjac ent to the hole, c aus ing them to fill the hole. When
the puzzle is uns c rambled, the original photo will appear in its
plac e. C lic k the photo to res et the puzzle (with different
s c rambling) and s tart over. You c an als o us e the links at the
upper left to reload the page and c aus e the puzzle to us e
different numbers of tiles : 3 x 3 , 4 x 4 , or 5 x 5 .

Hacking the Hack

You c an manually modify the puzzle by pas s ing any of the


following parameters to the app. I s ugges t experimenting with
thes e by entering them in your brows er's addres s bar:

group_id

T he group I D of the Flic kr group to pull images from. By


default, the P H P app us es the I D of the Squared C irc le
group, whos e images make exc ellent s quare puzzles .

page

T he page number of images to load (6 per page). I f you


don't s pec ify this , you'll get a random page.

idx
T he partic ular image on the page (from 1 - 6 ) to us e to
make the puzzle.

TD

T he tile dimens ions of the puzzle. I f you s pec ify 4, the


puzzle will be 4 tiles wide by 4 tiles high. T his parameter
is pas s ed direc tly to the Flas h movie. I f it is left
uns pec ified, it defaults to 5.

For example:

http://www.yourdomain.com/flickrPuzzle.php?page=2&idx=4

A lthough it's not inc luded here, you'll find the s ourc e c ode for
the 2 K Flas h movie that animates the puzzle at
http://www.krazydad.c om/flic krP uzzle/.

See Also

[Hack #50]

[Hack #41]
Hack 49. Make a Photo Mosaic

Using Flickr, any portrait can be more than the sum of its parts.

P hoto mos aic s c ompos ite artworks in whic h the mos aic tiles are
thems elves photographs were firs t invented by J os eph Franc is at
the R/G reenberg ad agenc y in the early 1 9 9 0 s . T hey weren't
popularized until the late `9 0 s , though, when Robert Silver, a
M as ter's s tudent at the M I T M edia L ab, c ame up with the idea
independently. Knowing he had a good thing on his hands , Silver
trademarked the name P hotoM os aic , applied for a patent, formed
his own c ompany, and s tarted s elling them. Soon, Silver's
beautiful and impres s ive mos aic s were s howing up in books , on
pos ters , and on magazine c overs .

N ot s o long ago, photo mos aic s would have been hard to make
on c heap des ktop c omputers at home. You needed fas t
proc es s ing s peeds , very large dis k c apac ity, and thous ands of
photographs to work with. T hes e days , the c heapes t des ktop
P C s have all the proc es s ing power and dis k c apac ity you need,
and s ervic es s uc h as Flic kr provide the final mis s ing ingredient:
a huge library of images .

T his hac k us es a P erl program I wrote to make photo mos aic s .


But before going down this road, you s hould know that there are
quite a few good third- party applic ations out there for making
photo mos aic s (although not all of them are well integrated with
Flic kr, yet).

Two other popular mos aic - making applic ations are


A ndreaM os aic for Windows
(http://www.andreaplanet.c om/andreamos aic /) and M ac O SaiX
for the M ac intos h (http://homepage.mac .c om/knarf/M ac O SaiX/).
A third exc ellent c hoic e is Flic krM os aic
(http://flic krmos aic .s ourc eforge.net). T his program, written in
J ava, will work on mos t platforms , inc luding L inux, and is
des igned to work s pec ific ally with Flic kr.

Making Great Mosaics

To build a photo mos aic , the s oftware s elec ts tiles from a large
pool of c andidate images . T he tiles are pic ked s o that eac h one
matc hes an area of a target image. For eac h tile, the s oftware
pic ks the c andidate image that is the c los es t matc h, typic ally by
c omparing the c olor dis tanc e in E uc lidean s pac e. So, a
c andidate image that is pinkis h would be c hos en for a tile
repres enting a red area over another c andidate image that is
green, bec aus e pink is c los er to red. T he c los er the tiles matc h,
the more the final mos aic will res emble the target image.

A number of fac tors affec t how well your photo mos aic s will c ome
out. L et's take a look at s ome of the things you'll need to
c ons ider.

The choice of target image

T he target image s hould reproduc e well at a very low res olution


(it s hould look good as a thumbnail). A ny detail you c an't s ee in
a very tiny thumbnail will probably not be vis ible in the mos aic ,
unles s you us e a lot of very s mall tiles .
I t is often bes t to edit the target image, us ing P hotos hop or
another image editor, before making a mos aic from it. Try
c ropping out a detail s uc h as a fac e or even an eye. Sometimes ,
it helps to inc reas e the c ontras t in the target photo; this will
c aus e a wider intens ity range in the c andidate tiles that are
c hos en.

I f you are us ing off- the- s helf mos aic s oftware, you might need to
res ize the target image down to a s maller s ize s o that the
mos aic s oftware does n't take forever trying to make a huge
image.

I n the s c ript introduc ed later in this hac k,


this is handled automatic ally. T he s ize of
the final mos aic is bas ed on the number of
tiles us ed.

The choice of candidate tiles

P hoto mos aic s are mos t effec tive when the s ubjec t matter of the
tiles has s omething to s ay (des c riptively, affec tionately,
ironic ally) about the target image. T hous ands of photo mos aic s
portraits have been c ons truc ted from generic s toc k photos of
s eas c apes and barns . T hes e are tec hnic ally impres s ive, but
ultimately meaningles s , unles s the s ubjec t of the portrait is a
s ailor or a farmer.

M y mos aic of Bottic elli's Venus


(http://www.flic kr.c om/photos /krazydad/4 8 9 4 5 0 9 /) c ontains
photos that matc h the word love, with lots of valentine hearts ,
people kis s ing, and people holding hands . M y mos aic of my
friend Fubuki (s hown later in this hac k, in Figure 7 - 1 4 ) c ons is ts
entirely of photos taken by Fubuki.

The overall number of candidate tiles to


choose from

G enerally, the more tiles you have to c hoos e from, the more
ac c urate the res ult will be. O n the other hand, you might like the
res ults you get when there aren't many c hoic es available; this
tends to produc e more abs trac t images , and s ometimes
ac c idents c an be c ool.

I have produc ed a number of mos aic s in whic h I us ed every


s ingle c andidate image. I n general, thes e reproduc tions don't
c ome out as faithfully as mos aic s in whic h you us e only a s ubs et
of a muc h larger pool, but it is a fun c hallenge to try to us e every
s ingle tile. I f you are forc ed to do s o, and you want a high- fidelity
res ult, it helps if the dis tribution of c olors in the target image is
c los e to the dis tribution of c olors in the c andidate images . I f
your target has a brown fac e, but mos t of your c andidate images
are green, you're going to get a green fac e. I f you have a c hoic e
of target images , pic k one that more c los ely matc hes the c olors
in your c andidate tiles .
The number of candidate tiles used to
overlay the target image

I us ually do a few runs trying different numbers of tiles until I


find a c overage I like. I prefer to try to us e the s malles t number
of tiles I c an get away with, bec aus e this makes the individual
tiles larger and eas ier to apprec iate. I f there are a gazillion
teens y, tiny tiles , you may as well be looking at the target image
its elf. H owever, there is a tradeoff between tile s ize and fidelity to
the target image: fewer tiles means les s fidelity. E xperiment with
different tile s izes and try to us e the larges t one you c an while
s till retaining good fidelity.

What You Need

To run the s c ript in this hac k, you'll need the Image::Magick P erl
module, whic h provides an A P I for the powerful I mageM agic k
image- proc es s ing library. You c an find it at
http://www.imagemagic k.org, or you c an download it from C P A N .

You'll als o need the following two modules , whic h I wrote:


Image::Mosaic and Image::FlickrSet. You c an find thes e on my web
s ite in the following arc hive, whic h als o c ontains a c opy of the
s c ript developed in this hac k:

http://www.krazydad.c om/s ware/J ims Flic krSc ripts .zip

Image::Moasic depends on Clone, whic h you c an obtain from


C PA N.

You'll als o need the s c ripts developed in [H ac k #3 3 ] and [Hack


#34] .

The Code

H ere's my s c ript for making photo mos aic s with Flic kr photos ,
us ing my Image::Mosaic module. C reate a file c alled makeMos aic.pl
and enter the following c ode (or grab the lates t vers ion from the
arc hive mentioned in the previous s ec tion):

#!/usr/bin/perl -s

#
# sub-sampling photo mosaic - Jim Bumgardner
#
# this script uses a subset of images from a larger set
# to make a mosaic against a target image
#
# work on reducing globals - store shared variables in an object..

use Image::Mosaic;
use Image::FlickrSet;

$photolist = shift;
$basepic = shift;
$max_images = shift;
$imagedir = shift;

$imagedir = $photolist if !$imagedir;


$photolist .= '.ph' if !($photolist =~ m/\.ph/);

$syntax = <<EOT;
pmosiac_subset.pl [options] <photolist> <basepic> [<max_images>]
Options:
-dupesOK Allow duplicate tiles
-noborders Reject images with solid-color borders or over 2:1
-noflops Images may not be swapped horizontally
-reso=\# Subsamples per photo - default = 7
-cellsize=\# Size of tiles - default = 20

EOT

die "$syntax\n" if !$basepic;

require "${photolist}";

#
# these are all command-line options
#
$reso = 7 if !$reso; # number of subsamples per tile = reso x res
$cellsize = 20 if !$cellsize;
$cellsize = 100 if $big;
$doflops = 1 if !$noflops && !$noflips;

$max_images = scalar(@photos)/4 if !$max_images;

my $imageset = Image::FlickrSet->new(\@photos, {imageDir => $image

my $moz = Image::Mosaic->new({reso=>$reso,
max_images=>$max_images,
imageset=>$imageset,
basepic=>$basepic,
noborders=>$noborders,
doflops=>$doflops,
cellsize=>$cellsize,
verbose=>1
});
$moz->generate_mosaic( );

Running the Hack

To us e the makeMos aic.pl s c ript, you'll need a target photo to


work with and a pool of c andidate photos . To make a mos aic of
my friend Fubuki, I firs t downloaded a lis t of Fubuki's photos to a
file c alled fubuki.ph, us ing this c ommand:

getPhotoList.pl -u fubuki

T hen I downloaded thumbnail vers ions of eac h of his photos ,


us ing the information in the file I had jus t c reated:

getSnaps.pl fubuki.ph

T his s tep is ac tually optional, bec aus e the


Image::FlickrSet module us ed in the
makeMos aic.pl s c ript will automatic ally
download photos if you don't already have
them. I like to do this s eparately, though,
as it's the mos t time- c ons uming part of
the proc es s .
N ext, I c hos e a s pec ific target image I wanted to make a mos aic
of. I did this by examining Fubuki's Flic kr s tream in my web
brows er to loc ate a portrait, right- c lic king the image, and s aving
the J P E G as fubuki_portrait.j pg. T he ac tual image I us ed is at
http://www.flic kr.c om/photos /fubuki/2 3 0 3 4 5 1 .

Finally, I made the mos aic by entering the following c ommand:

makeMosaic.pl fubuki fubuki_portrait.jpg 800

T he firs t argument referenc es the name of the fubuki.ph file that


c ontains the lis t of c andidate photos . I t is als o us ed to s pec ify a
s ubdirec tory, fubuki/, to find the thumbnails in. T he s ec ond
argument indic ates the name of the target image file. T he las t
argument, 800, indic ates the approximate number of tiles to us e
in the mos aic . T he number ac tually us ed might be s lightly more
or les s , in order to fill out the rec tangular s hape of the mos aic .

By default, the s c ript produc es a low- res olution vers ion of the
mos aic . I generally try a few different vers ions (experimenting
with editing the target image and altering the number of tiles ) till
I find one I like. I f you like the res ult, you c an produc e a high-
res olution mos aic us ing the -big option:

makeMosaic.pl -big fubuki.ph fubuki_portrait.jpg 800


When you us e the -big option, the s c ript will automatic ally
download large vers ions of the tiles that will eventually be
c hos en to be us ed in the image. T his s aves time, bec aus e you
don't need large vers ions of every s ingle c andidate image; you
jus t need the thumbnails , unles s the image goes into the final
mos aic .

Figure 7 - 1 4 s hows how my mos aic of Fubuki c ame out.

Figure 7-14. Fubuki mosaic


P retty s weet, eh?

How It Works

I f you're interes ted in the nitty gritty, I s ugges t taking a c los er


look at the Image::Mosaic module, whic h does mos t of the heavy
lifting.

T his module is written to be s ervic e- agnos tic ; it does n't know


anything about Flic kr. I ns tead, it works with an iterator c las s ,
whic h provides a lis t of images to work with. T he iterator c las s
mus t implement a method c alled get_image(), whic h retrieves
images one at a time. I des igned Image::Mosaic this way s o that it
c an be us ed with other image s ervic es , s uc h as G oogle I mage
Searc h, or with my own c ollec tions of photographs . M y Flic kr-
bas ed iterator c las s is c alled Image::FlickrSet. T his c las s is
des igned to work with the image lis ts produc ed by the
getPhotoLis t.pl s c ript from [Hack #33] .

Image::Mosaic performs four main s teps :

1. E xamines all the c andidate images and rec ords their


overall luminanc e values . D uring this s tep, Image::Mosaic
c alls the image iterator's get_image() routine and as ks
for thumbnail- s ized images . I f Image::FlickrSet, our
iterator, c an't find a partic ular image referenc ed in its
image lis t, it will download the thumbnail from Flic kr.
Image::Mosaic rec ords the luminanc e values to build an
index s o that the images c an be grouped by luminanc e,
whic h s peeds up s tep 3 , in whic h we s elec t tiles for the
mos aic .

2. Sets up a data s truc ture des c ribing eac h of the c ells in


the target image that will be oc c upied by a tile. For eac h
c ell, it rec ords the c olors c ontained in that c ell in the
target image. To s peed things up, the target image is
reduc ed in s ize to matc h the s ubs ampling res olution
(whic h defaults to 7 ), s o that eac h c ell c ontains no more
than 7 x 7 pixels . T he c ell lis t is s orted s o that c ells
that c ontain edges are res olved firs t; this produc es a
better- looking final res ult.

3. Selec ts the mos t appropriate c andidate image to fill


eac h target c ell. For eac h target c ell, a s ubgroup of
c andidate images is c hos en, us ing the luminanc e group
c los es t to the target c ell. E ac h of the c andidates in the
s ubgroup is evaluated for the target c ell by c omparing
the differenc es in the c olor values . T he c andidate with
the fewes t differenc es (the c los es t in the RG B s pac e) is
c hos en. I f it fails to pic k a tile bec aus e all the tiles in
the luminanc e group have already been s elec ted for
other c ells , it looks further afield, at nearby luminanc e
groups .

4. L oads in the s elec ted tiles and builds a c ompos ite image
from them. D uring this s tep, if the -big option was
employed, larger vers ions of the s elec ted tiles will be
downloaded by the Image::FlickrSet module, as
nec es s ary.

Hacking the Hack

A lthough s ome people might feel that photo mos aic s are pas s é,
there is s till enormous potential for innovations in making them.
For example, while exis ting photo mos aic s oftware produc es
mos aic s with s quare or rec tangular tiles , there is c ertainly no
reas on why photo mos aic s have to have s quare tiles on a
rec tangular grid.

Try us ing hexagonal tiles , diamonds , or other s hapes . H ow about


a hexagonal tiled mos aic res embling a honeyc omb, in whic h all
the tiles c ontain images of bees and flowers ? Try rotating the
tiles , or giving them more randomized plac ements . E xperiment
with c irc ular tiles arranged in a Fibonac c i s piral, like the s eeds
in a s unflower.

T he tiles don't need to have hard, s harply defined edges , either.


You c an us e image mas king to give the tiles fuzzy edges that
blend into eac h other.

Finally, photo mos aic s do not need to be s tatic piec es of art that
hang on a wall. You c an build an interfac e, us ing Flas h or A jax,
that will make your mos aic interac tive, perhaps providing
individual photo c redits for the tiles or making the tiles c ome to
life. I 've c reated s uc h interfac es for my C overP op web s ite
(http://www.c overpop.c om), whic h c ontains interac tive mos aic s
built from various s ourc es . See the C overP op FA Q
(http://www.c overpop.c om/faq/) for more information about
building interfac es for interac tive mos aic s .

See Also

[Hack #33]

[Hack #34]
[Hack #44]

[Hack #43]
Hack 50. Make a Slideshow

PHP and Flash combine to create eye candy with extreme


f lexibility.

I n [Hack #41], we built an app that dis plays a grid of images .


Wouldn't it be nic e to get thos e s ame images to appear in an
animated s lides how? T hat's what this hac k is about.

What You Need

T his hac k us es a modified vers ion of the s c ript developed in


[Hack #41], s o you'll need to have s uc c es s fully c ompleted that
hac k before s tarting this one. You'll als o need a web s erver with
P H P 4 s upport.

I n this hac k, we'll be making a Flas h movie that is c ompatible


with Flas h 7 . You'll need a vers ion of M ac romedia Flas h that is at
leas t as rec ent as Flas h M X 2 0 0 4 .

The Flash Movie

I f you're a programmer who has never learned Flas h, you'll like


this hac k, bec aus e the movie requires virtually no authoring
us ing the Flas h U I (whic h is artis t- friendly but hac ker-
unfriendly). I ns tead, the effec ts in the movie are ac c omplis hed
exc lus ively via A c tionSc ript, Flas h's s c ripting language.

C reate a text file c alled s lides how_s cript.as and add the following
A c tionSc ript c ode:

// Basic Looping Slideshow for Flash 7


//
// - Jim Bumgardner
//
// Parameters:
// flickrSnaps - list of server/id/secret triplets (delimited by
// timeBetweenSlides (milliseconds)
// fadeTime (milliseconds)
// debug (adds status msgs)

flickrSnapAry = _root.flickrSnaps.split(',');

// Create containers/loadees here...


containers = [];
curSlide = 0;
curSlot = 0;
if (!timeBetweenSlides)
timeBetweenSlides = 5000;
if (!fadeTime)
fadeTime = 3000;

doNextSlide = function( )
{
clearInterval(this.intH);
curSlide = (curSlide + 1) % flickrSnapAry.length;
this.altSlot.doLoad(curSlide);
}

fadeInStep = function( )
{
var r = (getTimer( ) - this.fxStart)/this.fxDuration;
if (r >= 1) {
r = 1;
clearInterval(this.intH);
this.intH = setInterval(this, "doNextSlide", timeBetweenSlides
}
// This applies an ease in/out to the fade effect
r = r*r*(3-2*r);
this._alpha = r*100;
this.altSlot._alpha = (1-r)*100;
// This next line provides the barn-door effect
// Comment it out for a more standard-looking
// cross-fade effect
this._xscale = r*100;
}

doFadeIn = function(duration)
{
this.fxStart = getTimer( );
this.fxDuration = duration;
this.fxStep = fadeInStep;
this.intH = setInterval(this,"fxStep",1000/30);
}

handleLoadInit = function(target)
{
// Center the slide
this._x = (Stage.width - target._width)/2;
this._y = (Stage.height - target._height)/2;
this.doFadeIn(fadeTime);
}

handleLoadError = function(target, errorCode)


{
_root.errMsg.text = 'got load error ' + errorCode + ' on image '
}

doLoad = function(slideNbr)
{
if (_root.debug)
_root.errMsg.text = "loading " + slideNbr + ' ' + flickrSnapAr
var fVars = flickrSnapAry[slideNbr].split('/');
this._alpha = 0;
this.itsURL = 'http://static.flickr.com/' + fVars[0] + '/' +
fVars[1] + '_' + fVars[2] + '.jpg';
this.itsLoader.loadClip(this.itsURL, this.loadee);
}

// Initialize two movieclips for slideshow


for (var i = 0; i < 2; ++i)
{
var mc = _root.createEmptyMovieClip('ctr_'+i,i+1);
mc.createEmptyMovieClip('loadee', 1);
mc.idx = i;
mc.doLoad = doLoad;
mc.doFadeIn = doFadeIn;
mc.doNextSlide = doNextSlide;
mc.onLoadInit = handleLoadInit;
mc.onLoadError = handleLoadError;
var loader = new MovieClipLoader( );
loader.addListener(mc);
mc.itsLoader = loader;
containers[i] = mc;
}
containers[0].altSlot = containers[1];
containers[1].altSlot = containers[0];

_root.createTextField('errMsg', 10, 10, 10, 480, 50);


_root.errMsg.textColor = 0xFFFFFF;
// Load the first slide
if (flickrSnapAry.length <= 0)
_root.errMsg.text = "No snaps specified";
else
containers[curSlot].doLoad(curSlide);

T hen, run Flas h and c reate a new projec t. U s e the M odify


D oc ument menu and s pec ify the following s ettings for the movie:

Dimens ions

5 0 0 x 5 0 0 pixels

Background Color

Blac k

Frame Rate

3 0 fps

Selec t the firs t frame of the movie on the timeline, and then open
the A c tionSc ript editing window by s elec ting Window
D evelopment P anels A c tions from the menu.

I n the A c tionSc ript window, enter the following one- line s c ript,
whic h c aus es the s c ript you jus t c reated to be inc luded:

#include "slideshow_script.as"
T hat's about all the Flas h authoring you need to do. A s you c an
s ee, mos t of the interes ting s tuff is in the A c tionSc ript file.

I f you like Flas h's text editor, feel free to


put the c omplete s c ript ins ide the
A c tionSc ript window, rather than us ing an
inc lude file. I prefer to keep my s c ripts
s eparate, s o I c an us e a more full- featured
text editor.

Save the projec t as s lides how.fla, and then s elec t File


P ublis h. T his will produc e a Flas h movie file c alled
s lides how.s wf, whic h s hould be approximately 1 KB in s ize. T his
is one of the nic e things about making A c tionSc ript- c entric
Flas h movies : they tend to be s mall and don't require annoying
preloaders .

U pload s lides how.s wf to your web s erver.

T he Flas h movie does not talk to the Flic kr A P I direc tly.


I ns tead, it ac c epts a lis t of Flic kr photos as one of its
parameters . T he lis t us es two kinds of delimiters . E ac h
individual photo is s pec ified by three s trings the s erver number,
the photo I D , and the photo s ec retwhic h are delimited us ing
s las hes . E ac h of thes e triplets is s eparated by a c omma. T hus , a
lis t of two photos looks like this :
29/44754794/29dbf5c75a,29/47126414/42ce67e060

T he Flas h movie takes this information and us es it to c ons truc t


U RL s that are us ed to pull the photos off of Flic kr. T he P H P web
page that loads the Flas h movie will build this lis t of photos by
querying the Flic kr A P I for information about your photos tream.

The Code

T he P H P s c ript is a modified vers ion of the s c ript developed in


[Hack #41] .

C reate a new text file c alled tes tSlides how.php and enter the
following P H P c ode:

<?php
ini_set("error_reporting ", E_ALL);

// Configuration stuff
$flickrAPIKey = "your API key goes here";
$flickrSharedSecret = "your shared secret goes here";

// Caching configuration stuff


$cachingenabled = false;
$dbUser = "your database username";
$dbPass = "your database password";
$dbAddress = "your database domain name (or localhost)";
$dbTable = "database table name";

// Create new phpFlickr object


require_once("phpFlickr.php");
$f = new phpFlickr($flickrAPIKey,$flickrSharedSecret);
if ($cachingenabled == true)
{
$f->enableCache(
"db",
"mysql://$dbUser:$dbPass@$dbAddress/$dbTable");
}
$f->auth( );
$token = $f->auth_checkToken( );

// Parse parameters
$page = 1;
if (isset($_GET['page']))
$page = $_GET['page'];

$per_page = 30;
if (isset($_GET['per_page']))
$per_page = $_GET['per_page'];

$fade_time = 2000;
if (isset($_GET['fade_time']))
$fade_time = $_GET['fade_time'];

// Find the NSID of the username inputted via the form


$nsid = $token['user']['nsid'];

// Get the friendly URL of the user's photos


$photos_url = $f->urls_getUserPhotos($nsid);

// Get a set of the user's photos


$photos = $f->photos_search(array("user_id" => $nsid, "per_page" =

$flickr_snaps = '';
$i = 0;
foreach ($photos['photo'] as $photo) {
if ($i++)
$flickr_snaps .= ',';
$flickr_snaps .= $photo['server'] . '/' . $photo['id'] . '/' .
}

print <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "ht
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-88
<title>slideshow</title>
</head>
<body bgcolor="#000000" color=white><?php
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/fla
width="500" height="500" id="slideshow" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="slideshow.swf?fadeTime=$fade_time&flick
<param name="quality" value="high" />
<param name="bgcolor" value="#000000" />
<embed src="slideshow.swf?fadeTime=$fade_time&flickrSnaps=$flickr_
quality="high" bgcolor="#000000" width="500" height="500" name="s
align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</body>
</html>
EOT;
?>

You'll need to modify the c onfiguration information at the top,


providing your A P I key, s hared s ec ret, and databas e information
if you want c ac hing. For more information about this , s ee [Hack
#41] .

U pload tes tSlides how.php to your web s erver, into the s ame
loc ation where you uploaded the s lides how.s wf file.

Running the Hack

To run the hac k, enter the addres s of tes tSlides how.php into your
web brows er's addres s bar:

http://www.yourdomain.com/testSlideshow.php

I f you have not yet been authentic ated, you'll s ee the Flic kr
permis s ions s c reen. O nc e you've granted permis s ion, the
s lides how s hould begin.

T he s lides how provides a trans ition effec t between photos by


us ing both an alpha c ros s - fade and a s c aling effec t that makes
eac h new photo appear to move like a c los ing door.

You c an modify the s lides how by pas s ing any of the following
parameters to the app:

per_page

T his c ontrols how many photos are us ed in the


s lides how before it loops .
page

T his c ontrols whic h page of photos from your


photos tream is loaded.

fade_time

T his s pec ifies , in millis ec onds , how long the c ros s - fade
effec t las ts . T his partic ular parameter gets pas s ed into
the Flas h movie.

H ere's an example U RL that pas s es thes e parameters to the


P H P s c ript:

http://www.yourdomain.com/testSlideshow.php?per_page=10&page=4&fad

Hacking the Hack

To keep things s imple, I 've written this s c ript to pas s only one
adjus table parameter, fade_time, to the Flas h movie, but I would
s ugges t adding a whole s lew of parameters s o you c an
c us tomize the s lides how to your liking.

I f you want to pas s additional parameters to the Flas h movie,


they c an be ac c es s ed from within the A c tionSc ript as predefined
variables (whic h are attac hed to the _root timeline). Follow the
P H P variable fade_time, whic h gets c onverted to the A c tionSc ript
variable fadeTime, to s ee how this works .
Bec aus e of differenc es between web
brows ers , parameters to the Flas h movie
need to be s pec ified in two different
loc ations within the <object> tag.

I would s ugges t adding additional trans ition effec ts to the


s lides how A c tionSc ript and adding additional parameters to
s elec t and c ontrol thes e effec ts .

A great number of web developers never get pas t learning one


language or tec hnology, but you'll find that c ombining multiple
languages and tec hnologies , as we have done here, c an greatly
enric h the kinds of end- us er experienc e you c an provide.

See Also

[Hack #41]

[Hack #45]
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

Bookshelf Project
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

categorization schemes, tags vs.


CGI scripts 2nd
code for hacks in this book

command line
running hacks on
community, Flickr
Contact status
contacts

limiting photo view ing to

statuses, Family, Friends, or Contact


Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

DOS command w indow (Window s)


Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

email
uploading photos to Flickr via
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

Family status (contacts)


Flash Player

Flickr
configuring privacy options for photos

email address for your account

setting up account

Tools page

Upload photos to Flickr page

Uploadr tool
Flickr address

choosing

Flickr community
contacts
groups
Friends status (contacts)
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

group photo pool


groups

full list, organized by topic

Groups feature

RSS feeds for


Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

inviting people to join Flickr


Index

[B] [C] [D] [E] [F] [G] [I] [M ] [O] [P] [R] [S] [T]
[U] [W] [Y ]

Mac OS X
Terminal
Macromedia Flash Player
more program
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

Organizr tool
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

permissions

limiting view ing to specific contacts

photo sharing [See sharing photos]


photostreams

RSS feeds for

PHP
online manual
PHP scripts 2nd
privacy settings 2nd

limiting view ing to specific contacts


Private setting
Public setting
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

RSS feeds
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

scripts
scrolling, controlling for script output
sets, photo
sharing photos 2nd

Flickr community

organizing photos w ith Organizr

permissions

limiting to contacts

sorting photos on Flickr

storing photos on Flickr

uploading from desktop

uploading from email

uploading from w eb brow ser


tagging photos on Flickr

via Flickr address (URL)

slideshows
view ing photo sets as
sorting photos on Flickr
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

tagging digital content


tagging photos

tags
RSS feeds for
Terminal (Mac OS X)
Tools page
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

uploading photos to Flickr

from email address

from your desktop

from your w eb brow ser


Uploadr program

URLs
Flickr address for photo sharing
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y ]

web browser
uploading photos to Flickr via

Windows
DOS command w indow

Uploadr program
Index

[B] [C] [D] [E] [F] [G] [I] [M] [O] [P] [R] [S] [T]
[U] [W] [Y]

Yahoo!

account, setting up

Hacks group

You might also like