One random photo from your flickr-stream
December 1st, 2007 |Note: Since ANY badge-url will work you can use randomFlickr with whatever photo you feel like, if your badge fetches the most recent photo of a category that’s what will be used, you’re only limited by what the badge-url can do
I’m a heavy flickr-user, trashing it with all my snapshots, useless party-pics, all kinds of stuff. And I like to use my flickr photos outside flickr, e.g. on my personal blog. Now there’s the flickr API and all kinds of wrappers and kits, but all of this is kind of hardcore stuff if the task as simple as: Gimme one random photo from my stream. randomFlickr.class can do this for you.
Download V 0.6
Applying filters requires PHP5+. There’s a PHP4 version available, too. GD Library 2 is required for image resizing, that should be included as a standard extension. If you plan to do anything above that I’d suggest having a look at the various available PHP-tools for flickr:
But if all you want to do is fetch a single photo then have a look at the randomFlickr Demo. Now for the documentation.
The initial bright idea was brought to me be an article I can’t seem to find anymore, but I’ll try to give proper credit. The class utilizes a flickr-feature: Javascript-badges. There’s a page to create a badge on flickr, which results in a JavaScript / CSS codeblock. While that works it has a few major downsides:
- it’s javascript where javascript definitely isn’t appropriate
- it doesn’t give control over the images themselves
- it only can fetch kind of small images
But what it does is it provides the necessary image data we then can process with PHP. For the development I used this badge-url I set up to fetch one random medium-sized image from my whole photostream. Click the link to see what the returned HTML/JS-Stuff looks like.
Focus
While building the class I always had one thing in mind: This is for one image, nothing more, so the class was built to offer a nice variety of things to do with that one picture, however doesn’t support anything beyond. The final result should achieve three goals:
- light-weight
- easy to use
- easy to integrate
Basic usage
Most of the code is kind of self-explanatory and, as I like it, heavily documented, so best you just browse through the class file you can download from the demo-page. Now for the class. It’s kind of hard to wrap my mind inside-out back to the start now that all is done, so I’ll do it the other way round and explain what’s happening from the usage point-of-view, that should work. So let’s have a look at how the thing is integrated on a webpage:
-
<?php
-
$badge = 'http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=m&layout=x&source=user&user=7353617%40N04';
-
$width = 400;
-
$height = 240;
-
$gray = true;
-
include_once('flickpic.php');
-
?>
This is the more ‘dummy-friendly’ way to integrate, since there’s hardly anything related to coding. Just replace the badge url with whatever badge you want, modify the size settings and you’re fine. The $gray-thing converts the image to grayscale, if set to true. Using the whole thing this way will result in an image linked to it’s flickr-page and doesn’t require anyone to write any php, or to alter any files. We’ll shortly reveal the real magic, so hold on for a more programmer-like approach giving you the details you want.
A few more details: flickpick.php
-
if ( !isset($_REQUEST['imageUrl']) )
-
{
-
try
-
{
-
$x = new randomFlickr($user);
-
if ( $badge )
-
{
-
$x->setBadgeUrl($badge);
-
}
-
$x->fetch();
-
}
Line 08 checks if an image-url has already been submitted. That’s not the case when including the file, so what’s about to be done is to display some nice HTML to display the image. try – catch is needed due the methods throw exceptions. In line 12 the randomFlickr-object is being created using a variable $user. This variable isn’t specified here, therefore will just be ignored. Then we check if a badge-url has been specified in $badge. If so, we change the object’s badge url according. Time to fetch some data on line 17.
A few words about the fetch()-method. It will check if there’s a user id specified (the ugly flickr user-id string, that is, due the badges don’t seem to work with the usernames). If so, it uses the default badge-url for 1 random image and passes that user-id. Easy. If there’s no user specified, the badge-url will be used as-is. That way there are four possibilities to get a valid result:
- specify a user and rely on the default url
- specify a full badge-url
- specify a user and a badge url
- specify nothing and pass the user-id to fetch() (will override a stored username for this one call only)
The method doesn’t really do much, just usual dirty regex-info-fetching, no great inventions there. Most important, it doesn’t retrieve the actual image, it just sets up meta-information, like dimensions, title and that kind of stuff. So let’s go on in the code of flickpic.php:
-
$src_post = ( $width ? "&width=$width" : '' ) . ( $height ? "&height=$height" : '' ) . ( $gray ? '&grayscale' : '');
-
$http = 'http://'. $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI'] . 'x') .'/'. $relpath;
-
-
print ( $x->getHtml(false, array('src_pre' => $http .'flickpic.php?imageUrl=', 'src_post' => $src_post, 'fixwidth' => $width, 'fixheight' => $height)))
The first line builds a parameter src_post, the next line uses the current directory (the ‘x’ is added to “simulate” a file if the home dir is being requested, otherwise we’s loose one directory here – just try, it’s stupid to explain) plus any specified relative path to build the path to this file for the output-generation later. Now the next line does some magic. It prints the result of the getHtml()-method which, obviously, generates HTML code. Let’s have a look at the method and the parameter, due this is one of the most flexible parts of the whole thing:
HTML is what we need
-
// @param string $sFormat the new format – anything you want, that is
So there’s the first parameter $sFormat. This parameter will, if specified, override the object’s default HTML-template (this can also be done permanently using the setDefaultHtml()-method). HTML-Template? Yessss! The class uses this default HTML to create the output: <a href=”{url}” title=”{title}” class=”{class}”><img src=”{src}” title=”{title}” alt=”{title}” {html_dim} /></a>, so nothing more than a link-wrapped image. BUT note the template-variables enclosed by {}. There’s a whole bunch of them available, namely:
- {title} title fetched from flickr
- {url} url for the link the image is wrapped with
- {src} image’s src
- {html_dim} image’s dimensions as html attributes (see getHtml() for details)
- {width} image’s width
- {height} image’s height
- {hwidth} width value used for the html-attributes (image’s width or fix width)
- {hheight} height value used for the html-attributes (image’s width or fix width)
- {fixwidth} value passed to getHtml() to use for width-attribute
- {fixheight} value passed to getHtml() to use for height-attribute
- {class} a string for a css-class
All these variables can be used in custom HTML-Templatecode to suite all kinds of possible ajax or whatnot needs, thus making the display as flexible as you like. But back to getHtml(). There’s a list of special parameters to pass as indices of an associative array (second method parameter $aParams):
- ‘fixwidth’: for the width=”" attribute of the <img>
- ‘fixheight’: for the height=”" attribute of the <img>
- ‘nativedim’: the image’s real dimensions will be used for width=”" & height=”"
- ‘class’: for the <a>, by default
- ‘src_pre’: inserted just before the image’s src
- ‘src_post’: inserted right after the image’s src
- ‘url_pre’: inserted right before the url to the image
Using those values the image source can be utilized as a parameter for a PHP script (that’s what flickpic.php does), giving us <strong>much</strong> more possibilities to control it’s appearance. All possibilites, that is. Now on to that part that’s responsible for generating the actual image:
Now for the image
-
$x = new randomFlickr();
-
$x->init('', urldecode($_REQUEST['imageUrl']));
-
-
if ( isset($_REQUEST['width']) || isset($_REQUEST['height']) )
-
{
-
$x->resize(( isset($_REQUEST['width']) ? $_REQUEST['width'] : false ),
-
( isset($_REQUEST['height']) ? $_REQUEST['height'] : false ));
-
}
-
-
if ( isset($_REQUEST['grayscale']) )
-
{
-
$x->applyFilter(IMG_FILTER_GRAYSCALE);
-
}
-
-
$x->send( 90 );
There you go. First of all a new randomFlickr-object is being created (the script is called again, so there’s no object there). Then the actual image is loaded with the init()-method. This method either uses the data already present within the object or any passed url (the urldecode() is necessary because the script generates XML-validating URLs, thus urlencoding all parameters. By the way the method can also be used to fetch any non-flickr image, if you only want to use it for the image manipulation the class offers). The init()-method accepts two parameters. The first one is for the image size. If not specified, the default size (large) will be used. Then for the probably most important feature the class has to offer: Intelligent image resizing:
- Only width / height specified: The image will be resized proportionally
- width & height specified: The image will be resized proportionally to fill the whole format, then will be cropped to it’s center
This way you can show your pictures in any unusual format, what’s not only cool but also handy if it comes to fitting them into your design. On with the code. The next thing we’re doing is we check for the grayscale-variable. If it’s set we apply the grayscale filter (we’re clever, aren’t we?). The applyFilter() method is a full-featured wrapper for the imagefilter-function, so have fun doing stuff!
Finally the last line sends the appropriate headers and the image data itself. So the endresult is kind of a recursive script (probably not, but sounds sophisticated) that doesn’t need much of editing to work for anyone, but provides a lot of flexibility if you’re willing to play around in flickpic.php.
Version History
-
2008-04-02: V0.6
There’s new options to choose different source-sizes. Specifying $size = “auto” will let the script guess which version to use based on the destination dimensions. This, however, may only work for close-to-standard formats, you might want to either leave everything as it is if it’s working or use one of the new constants to explicitly define which source to use:
- xxs = 75px by 75px
- xs = 100px by X
- s = 240px by X
- m = 500px by X
- l = 1024px by X
- xl = your uploaded file
Note that flickr always uses the bigger side to scale the sizes, so portrait-format images will be scaled to 1024/500/240/100 Pixels height, while landscape-format images will be scaled to 1024/500/240/100 Pixels width. The three smaller sizes are the ones being used by flickr itself and are fixed-size.
Oh, and I switched the Demo-Page from XHTML 1.1 back to XHTML 1.0, due to the inability of some browsers to handle the application/xml mime-type. Welcome to randomFlickr, Win IE6 Users. -
2008-03-19: V0.5
now falling back on CURL if allow_url_fopen is disabled. As the title says the script now checks if allow_url_fopen is enabled, if not it tries to fall back on the CURL-library. One of both should be available on every hosting plan and I hope compatibility increased.
-
2007-12-07: V0.4
PHP4-Version: There now is also a PHP4-Version. Please note that image-filters are only available in PHP5, thus the PHP4 version can’t convert your images to grayscale, thus resizing + cropping work perfectly fine.
[...] you are looking to implement something like this on your site, I suggest you check out knoDocBlog and read through his [...]
Hello!
Congratulations for the work done!
I tried the script, I followed the instructions, but does not work and I have this error:
Parse error: syntax error, unexpected ‘{‘ in /home/paperino/public_html/flickpic.php on line 11
I hope your help.
Thanks!
I forgot: I downloaded the files from the site and used without making any modifications (randomFlickr.class.php and flickpic.php).
There may be errors or bugs?
Thanks again!
Hi Paperino,
probably you run a PHP version < 5?
The script uses PHP5′s OOP-features. You can find out which version you have with a simple php-file containing nothing but:
<?php phpinfo(); ?>
Thanks for the answer!
I checked on my server and I have PHP Version 4.4.7
The scripts can work properly with this version?
Thanks anyway.
Hi Paperino,
I rewrote a few sections and now it _should_ be compatible with PHP4. However I can’t test it because I don’t have access to a PHP4 environment by now, so you’ll have to try. The files are to be found on the download page: http://dev.kno.at/flickpic/dl.php
You will probably have to rename them to .php instead of .php4, depending on your server configuration.
Please note that the filters (turning into grayscale etc.) are only available in PHP5, so you’ll not be able to apply these.
Also you need the GD Library 2 for the script to work, but that should be pretty much of a standard by now.
Hope this version works for you :)
Hello. Im having a bit of trouble getting the plugin to do its thing…I keep getting this error:
“no pic: could not fetch data from batch
http://www.flickr.com/badge_code_v2.gne?show_name=1&count=3&display=random&size=m&layout=v&source=user&user=38864967%40N00”
I tried the default one:
and still get the error.
do you know what im doing wrong….Thanks in advance
Hi Mark!
I just tested your badge-url on the demo-page and it worked fine. Probably there’s been a typo in your script?
Do you use the PHP4 or the PHP5 version?
Hi.
Im using php 5 here the link to the page
staging.littleradioev.com
I uploaded everything is there anything. do I have to change in the php files to make it work?
Hi Mark,
if you followed the instructions like here: http://dev.kno.at/flickpic/ everything should work just fine. If I try to access flickpic.php at your URL it says that it can’t include randomFlickr.class.php – you might want to check if it’s uploaded and in the correct directory.
Otherwise I’d suggest you try to start from scratch in an empty document, with the files down- and uploaded freshly.
As said above, if I use your URL in the test-file it works just fine, so I’m pretty sure sth. went wrong during the installation :)
Hey kno,
its me again…so I started a new site to test it and got this error:
Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 199
Warning: file_get_contents(http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=m&layout=x&source=user&user=7353617%40N04) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 199
no pic: could not fetch data from badge http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=m&layout=x&source=user&user=7353617%40N04
What do you think? here is the site: http://test.sansrival.la/
Hey Kno,
Its me again, so I started over and got a new error message:
Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 199
Warning: file_get_contents(http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=m&layout=x&source=user&user=7353617%40N04) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 199
no pic: could not fetch data from badge http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=m&layout=x&source=user&user=7353617%40N04
Im a real noob and dont understand it. heres the site I loaded it on: test.sansrival.la
Thanks so much for your help.
so dreamhost got back to me and said the disable that function and said they use Curl?
anyway to get the script to work with curl?
here is the dreamhost wiki on it:
http://wiki.dreamhost.com/index.php/CURL
Hi Mark!
I just updated the files and they should now work with CURL as well. Hope it now works for you!
If not you know where to find me ;)
Hey Kno, thanks you so much for all your help. I’m getting another error. (test.sansrival.la)
Warning: getimagesize() [function.getimagesize]: URL file-access is disabled in the server configuration in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 243
Warning: getimagesize(http://farm3.static.flickr.com/2222/2259461975_885eae1852.jpg) [function.getimagesize]: failed to open stream: no suitable wrapper could be found in /home/.keekum/markgil/test.sansrival.la/randomFlickr.class.php on line 243
Weird Flamingo
Again…thanks so much for everything…you’ve been such a trooper. And please let me know if there is anything that I can do for you.
Just updated the remaining remote file access sections of the script, it should eventually work with falling back on CURL.
Curious if it actually is ;)
OMG….ITS WORKING!!!!!!! THANK YOU SOOO MUCH. Youve been such a great help
This worked great for me. Thank you for sharing it.
About image-sizes (Original at martinjy.com):
[...] I uploaded original 3000px wide shots – that’s Flickr doing the compressing somewhere along the line. I think what might be happening is that the image in the Flickr feed (which the code uses) is small-ish and slightly enlarged for [...]
[...] I can help with the crispyness by the way. The randomFlickr-script uses the medium-sized version, which is just 500 by somewhat pixels big, therefor resulting in lower quality.
If you want to use larger files you can achieve this easily by doing the following:
Open randomFlickr.class.php
Find line 240: $this->sSrc = $matches[0] . ‘.jpg’;
Change the last part ‘.jpg’; to ‘_l.jpg’ (underscore + lowercase-L).
The script will then use the “large” image-version, which is 1024 by somewhat, so big enough for your needs :) I’ll add this to the comments on the script-page too, so others can find it.
2008-04-02: V0.6: choose which source-size to use or rely on a very rudimentary guessing-function, see release notes for details. Demo-Page switched back to XHTML 1.0 (from XHTML 1.1), welcome Win IE6 Users.
[...] just tweaked randomFlickr a bit and thus am releasing V0.6. Not because it’s a huge update, I just feel like releasing [...]
Thanks for stopping by my site Christian and thanks for the _l tip, but I couldn’t get it to work. Flickr’s naming convention seems to be different/changed? I left more detail in the comments on my site. Hope you can fix it!
[...] just tweaked randomFlickr a bit and thus am releasing V0.6. Not because it’s a huge update, I just feel like releasing [...]
Hi!
Nice Plugin!
It is possible to show more than only one picture of my flickr badge?
Hey min,
currently the plugin doesn’t support multiple images, but I’ll be extending it to enable exactly that, thus I can’t tell when this extension is going to happen due to I’m working on lots of things at the time :)
As a “workaround” you could install it with multiple, different set-up badge-urls, however this will slow things down quite a bit since every badge needs to be fetched over the web, being a speed- and a stability issue (sometimes the badge-fetching fails)
Great script.
Just having one issue.
I’ve set the size on my site to width=490 and height=683 with the badge URL
http://www.flickr.com/badge_code_v2.gne?count=1&display=random&size=l&layout=x&source=user&user=80837134%40N00
It all works great with size set to ‘m’ but if I choose auto or manually set the size to ‘l’ the picture doesn’t load. And without setting the size to ‘l’ the picture doesn’t look crisp at all.
Looking at the image it is trying to load the correct image with the _b.jpg extension but there is some reason why it doesn’t get processed.
I get the error
Warning: imagecreatefromstring() [function.imagecreatefromstring]: Data is not in a recognized format in /homepages/41/d153278603/htdocs/fredbrewin/randomFlickr.class.php on line 355
no pic: could not create from http://farm3.static.flickr.com/2135/2271687098_936514df62_b.jpg
I see Martinjy had a similar problem on his site but this appeared to be fixed by the new release. In fact. Upon replacing my image address with emptyperfection.com instead of fredbrewin.com it does in fact perform as I would like.
So, what am I doing wrong? Do I need to edit the class or should setting the size to ‘l’ just work?
Thanks so much for your time in developing this and replying to my message.
Hi Fred!
Sorry for the late reply, but I played around a bit trying to reproduce your error, however I couldn’t.
Usually setting the size to ‘l’ should do the job, it looks like there’s a problem fetching the data but I just can’t think of a good reason.
All that’s left of a difference is that your uploaded photos only go as far as up to “Large”, there’s no “Original” version, so there might be a problem with mixed up filenames or sth, however that shouldn’t be the case from what I see in the code you posted here – the image that can’t be loaded clearly exists.
Hi,
congratulation for your script but I found the documentation not so easy… I’m not able to use it on my wordpress web site, could you write a step by step installation guide ?
Thanks!!
Ciao
Nice script, well done.
One problem though, l can’t get the larger sizes to work at all. I ‘ve tried opening access up on my Pro flickr account so all images are public domain but this didn’t seem to be the problem.
The script only seems to work if I use $size = “m”; all larger sizes ( $size = “l”; or $size = “xl”; ) fail to work and the webpage is an empty link…
Not sure if I missed something or my Flickr account is configured incorrectly…
Hello there,
Used your script on my website, thank you :-)
This is the script I was looking for! I’m trying to get it to work inside a WordPress template, any suggestions? I can get it to work fine on a dev page, but when I add it to the header file of the wordpress theme, it breaks the img src URL.
Hey Ramsey!
I’m not sure how WordPress would break the URL – do you run any plugins that rewrite URLs, probably?
Other than that I can just guess wildly, doesn’t make much sense. I’m running the script as-is on the front page of my blog (it’s not random because the badge-url I use always gets me the most recent picture from my mobile-phone shots), so it should work with WordPress.
Here’s what my setup looks like:
themes/theme_name/flickpic/flickpic.php
themes/theme_name/randomFlickr.class.php
in sidebar.php:
$badge = ‘badge url’;
$relpath = ‘./wp-content/themes/theme_name/flickpic/’;
Relpath has to be relative to your blog’s root, as the source-url for the picture will point to flickpic.php
Hope that helps :)
I think your work promises precisely what I want. A random picture from my photostreem with a specific tag. But.. What the hell must I do to make it work??? a description with verbs in it. Ciao J.
Hey John,
have you had a look at the Demo-Page? There’s an example there of how to include the file.
Im with John on this. I have downloaded the php scripts, made sure my server is set, I copied your demo page just to test with and I dont get an image. I think it has to do with html integration. but I dont know.
Hm you’ll have to give me something more if you want me to help. “It doesn’t work” is sad, but I can’t really do anything but guess what could be wrong.
A link to a page where you tried it, probably drop me an e-mail with the php-script or whatever.
Yeah, I was being a bit vague. Any help you can give would be great. I dont know much about PHP. I sent you emails but maybe they ended up in your trash folder. I put the php code on the server and created a page using your “Include this” code. here is a link: http://cathoderay.net/phpTest/phpTest.php
I am not very good at all of this stuff, at least on this very technical end of things, so please bare with me.
Does this plug in take a random photo from your flickr photostream and post it as a blog entry automatically? Is it limited to a sidebar? Perhaps I am misunderstanding it all? Does it have to have a specific tag or can this simply go grab a random image and post it?
Essentially I am looking for a plugin that can automatically (scheduled) fetch and posts a random image from my stream or maybe some specified sets.
Your plugin appears to be the closest thing to what I am looking for. Any suggestions would be helpful.
Hi Kno
Hope you are well! This is brilliant. I have it working a treat! I was wondering though if there is a way I can print the title of the image above the image as well??
It would also be great if a class could be attached to it…
this is the page I am working on.
http://www.contentof.com/random2.php
where it says “An image from my flickr” it would be great if it was he title instead..
Many thanks
Claire
Hey Claire,
you can actually use the title of the image, but you’ll need to dig a little deeper into the coding-thingy. Open flickpic.php and find line 28:
print ( $x->getHtml(false, …
Replace false, by:
‘<h1>{title}</h1>’ . $x->getDefaultHtml(),
You can use any Markup you like, just put {title} wherever you want to display the title.
For further details on customization you can have a look at the randomFlickr.class.php, you can pass on whatever HTML you’d like to use and thus format/use the picture to your liking.
Hey Spencer,
what this script does is, essentially, fetch the data for the first photo of any badge-url you supply. It is as flexible as the badge-url-generator flickr offers, so you can pretty much control what you want to get.
It does not post anything anywhere though, it only fetches data and generates HTML to display stuff :)
Kno,
I got the php5 version to work, but I need to drop down to the php4 ver. When I do I am getting “Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in … line 190″. (http://tjameswhite.com/dev/test.php) Any thoughts?
Hey Tim,
I just re-checked the file, and there are still two functions labeled “public function” and “private function” – both keywords, public & private, are not working with PHP4 as far as I’m concerned, so by removing them you should be fine. Unfortunately I don’t have a PHP4 environment to back-test, so errors like that sneak in easily.
You can also just re-download the script, I updated the online version.
Let me know if it still doesn’t work!
Kno,
Bravo! That seems to have done the trick, thanks. And all because WP 2.7 won’t run under PHP 5 like its suppose to.
Kno,
FYI: the script works with video as well. it grabs the flickr-generated screen shot and displays it just fine. (Something I hadn’t thought about until testing pulled one of my videos up.)
I know this post is old but… This is the closest thing to what I am trying to do. I could not get the original size photo to work.
I edited the randomFlickr.class.php – instead of calling the original size “xl’, I changed it to be “o” and it worked.
The problem I am having now is that it is not pulling a random image from my whole Flickr library. It seems to be pulling the same several images over and over again. I have over 2000+ images to randomly pull from, but I have seen a couple of photos up to 5 times in any test where I refresh the images.
How is the image pulled randomly? Is there a way to pull images from a specific set with this bit of code?
Thanks.
Hi bro.
I the beginner.
I wish to show to you,scandal story
http://www.arielrebelnude.co.tv