Placed in: Home arrow Programming arrow Actionscript arrow A Flash image viewer by reading directory contents
A Flash image viewer by reading directory contents

As a web developer or programmer, you want to make your software as dynamic as possible. This means that you can easily change the code or contents, without digging in and rebuilding your original source.

(Flash) Image rotators are a pretty effective and attractive way to show your images. Most of the times, these Flash image rotators are not dynamic and need to rebuild every time you want to change the images. Here's a solution for this problem, because I'll explain how to create a Flash image viewer by reading directory contents.

Flash Image Rotator

Just place all images you want to rotate in the same directory as the Flash file and this script does all the work for you. If you want to add an image, just place it online and the Flash viewer will show it.

Check out the demo of the Flash image viewer, or download the flash image viewer by reading directory contents from the download section.

Preperations

First things first. You'll need to have the following to bring this project to a success:

  • A PHP editor like Dreamweaver
  • A couple of images having the same dimensions (Mine are 400 x 100 and downloaded from socwall)
  • A server supporting PHP
  • Flash Professional for the viewer
  • A little bit knowledge about XML, PHP, ActionScript and Flash is enough

Everything checked? Proceed to the next step.

Create the XML file with PHP

Now we'll need to get the directory contents using PHP. By manipulating the header type of the PHP file, you can let any other program "think" this file is a XML file. You'll need to do this in order to let Flash read the (fake) XML file.

Comments are added in the source to explain what the code does.

<?php
// Set which extensions should be approved in the XML file
$extensions = array
(
  'jpg', 'JPG',
  'png', 'PNG',
  'gif', 'GIF',
  'bmp', 'BMP'
);
 
// Echo the header (XML)
header("Content-Type: application/xml;charset=ISO-8859-1");
 
// Prepare the XML file
echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\r\n";
echo "<images>\r\n";
 
// Get the files from the current directory
if (file_exists ("./"))
{
  if (is_dir ("./"))
  {
    $dh = opendir ("./") or die (" Directory Open failed !");
    
    // Prepare the images array
    $imgs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($imgs, $file);
      }
    }
  Closedir ($dh);
  }
  
  // Sort the array
  sort($imgs);
  
  foreach ($imgs as $img)
  {
    // Return all images in XML format
    echo ('   <image src="' . $img . '" />');
    echo "\r\n";
  }
}
echo "</images>";
?>

Save the file as source.php. Upload it in the directory on your server where you have the images stored. When viewing the PHP file, you should get something looking like this.

<?xml version="1.0" encoding="ISO-8859-1"?>
<images>
   <image src="01.jpg" />
   <image src="02.jpg" />
   <image src="03.jpg" />
   <image src="04.jpg" />
   <image src="05.jpg" />
</images>

If everything is correct, you can go to the next step: Creating the Flash viewer.

Flash Viewer

I'm not going to explain step by step how to create the Flash viewer, you can learn from my source code.. Basically, the Flash file looks like this.

Flash Build
  1. background: Just the background of the Flash file
  2. imgholder2: Movieclip that holds one image
  3. imgholder: Movieclip that holds another image
  4. hidingbox: Movieclip that slowly fades out before the first images shows
  5. errorbox: Dynamic text that can hold error messages

Just make sure the FPS of the file is set to 24.

Actionscript

Here is the actionscript code I created to rotate the images, slowly showing them after another. Create a new layer on top of all layers and call it "AS". Press "F9" to insert the ActionScript code.

Comments are added (as usual).

 
// settings
var changingspeed = 300;
 
// stop the frame
stop();
 
// errorbox is not visible
errorbox._visible = false;
 
// Prepare the images
var totalnrimg;
var curnrimg = 0;
 
// Prepare the images array
_root.img = new Array();
 
// Load the XML file
var xmlData = new XML();
xmlData.ignoreWhite = true;
xmlData.onLoad = processXMLData;
xmlData.load("source.php");
 
// When XML data is loaded, execute this function
function processXMLData(success)
{
 if (success)
 {
  // Loop through the XML file
  for (i = 0; i < this.childNodes.length; i++)
  {
   xmlNode = this.childNodes[i];
   for (j = 0; j < this.childNodes[i].childNodes.length; j++)
   {
    _root.img[j] = xmlNode.childNodes[j].attributes.src;
   }
  }
  totalnrimg = _root.img.length;
  // Load the first image
  loadMovie(_root.img[curnrimg], imgholder);
  curnrimg++;
  // Load the second image
  loadMovie(_root.img[curnrimg], imgholder2);
 }
 else
 {
  errorbox._visible = true;
  errorbox.text = "XML file could not be found";
 }
}
 
var showingHidebox = 100;
var isShowing = 0;
var showingFirstImg = changingspeed;
var firstIsShowing = true;
_root.onEnterFrame = function()
{
 // Slowly show the image
 hidebox._alpha = showingHidebox;
 if (showingHidebox != 0)
 {
  showingHidebox--;
 }
 
 // Slowly hide the first image
 imgholder._alpha = showingFirstImg;
 if (firstIsShowing == true)
 {
  showingFirstImg--;
  if (showingFirstImg <= (0-changingspeed/2))
  {
   firstIsShowing = false;
   curnrimg++;
   if (totalnrimg == curnrimg)
   {
    curnrimg = 0;
   }
   loadMovie(_root.img[curnrimg], imgholder);
  }
 }
 if (firstIsShowing == false)
 {
  showingFirstImg++;
  if (showingFirstImg >= changingspeed)
  {
   firstIsShowing = true;
   curnrimg++;
   if (totalnrimg == curnrimg)
   {
    curnrimg = 0;
   }
   loadMovie(_root.img[curnrimg], imgholder2);
  }
 }
}

Export your file to swf and upload it to your server. Load the flash file to test your movie and check if it's working. If everything is done correct, the images should show up nicely.

Conclusion & download

You could think about reading the size of the images so it would be totally dynamic. Other than that I think this is a pretty nice way to slowly rotate and show images that are from one directory.

If you don't want to animate the viewer, just could also use the PHP Random Image Rotation.

You can download the flash image viewer by reading directory contents from the download section.

If you're looking for an image viewer for your website, you can also check out 22 beautiful image galleries for your website.


Tags:  xml php actionscript flash tutorial

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
Digg!Reddit!Del.icio.us!Facebook!StumbleUpon!
Comments
Add NewSearchRSS
juan - thanks dude   2008-07-18 04:14:44
Gravatar image hey marco thanks for the code, it helps me a lot with a proyect...

thanks again dude!

:lol:
Simon Radford   2008-07-21 10:12:00
Gravatar image Hi
This is a great script, but I tried to open the .fla file in Flash 8 and got an error.
I also tried to re-create it from the flash code above but it was just black, any ideas what I'm doing wrong?
Simon
Marco - What error?   2008-07-27 16:59:38
Gravatar image Hi there Simon,

What is the error that Flash 8 is giving? Please note the FLA file is created with Flash CS3.

You can also try contacting me through the contact form and send me your FLA file so I can check.

Good luck!
ebonee - flash   2008-10-28 23:00:01
Gravatar image Hi, thanks for the useful html code, but I'm sorry I don't understand how to make it work on my site. I don't know what part of the code to copy, or what I need to make it work. I already have some flash images on my site, so I think i already have the appropriate software to make it work. Could you break it down to really simple language for me? Thanks. Please reply to me email address.
Nick Cosper - Randomize?   2008-08-19 01:35:39
Gravatar image This is a great script! It is working perfectly for my needs. Any way to randomize the image display? That would be great!
Thanks
Marco - ActionScript knowledge   2008-08-19 09:34:24
Gravatar image Hi Nick,

Good that this script it working out for you!

Do you have AS knowledge? If so, just make a function that will randomize the "_root.img" array.

Good luck!
Leif - faster transition   2008-09-12 06:55:40
Gravatar image How would you speed up the transition?

I also noticed when it first starts, it blows through the first image fast and transition right to the next.
Leif - ooo also -   2008-09-12 06:57:04
Gravatar image I wouldn't mind seeing some code for randomizing the images.
Leif   2008-09-12 07:01:41
Gravatar image Really, what I would like to do is have the image stay up a little longer before changing, maybe 10 seconds, but then I want the transition time to be faster in between.

I played with the changingspeed variable and the showingHidebox, but this seems to create some bugs - some images would zip by while it would pause on others, for not I put them back to what they were - I will have to dig in this some more after I sleep.
Leif   2008-09-12 17:57:28
Gravatar image alright - I found a blurb of actionscript for writing a function that randomizes the array, no problem. But it is still buggy when it comes to the length of time it displays each image. Using your code, unchanged, it will display the first photo for about 4 seconds, then the next for about 13 seconds, then 17 seconds, then 13, 17, 13, 17 and so on.

wouldn't it be easier to just use a tween and control that in the actionscript?
Nick Cosper   2008-09-17 19:05:13
Gravatar image Leif,
Would you care to share what you did for actionscript and randomization? I posted a while back, but never was successful implementing the actionscript. I am totally unfamiliar with actionscript!
thanks
Leif   2008-09-18 07:08:25
Gravatar image I found a few different solutions, some better than others for different reasons, this is the one I ended up using. Just add this function to your actionscript:

[code]function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
for (it = 0; it
Leif   2008-09-18 07:12:12
Gravatar image Sorry, the [code][/code] brackets don't seem to work right - let me try that again.

so here is the function:

function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
for (it = 0; it
Leif   2008-09-18 07:16:20
Gravatar image okay last try.

function:

function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
for (it = 0; it < _length; it++) {
el = mixed[it];
mixed[it] = mixed[rn = random(_length)];
mixed[rn] = el;
}
return mixed;
}

add this line:

_root.img = mixArray(_root.img);

before this line:

totalnrimg = _root.img.length;

that way, you will randomize the array before you load the first image.

the time it displays each image is still quirky for me though...
Nick Cosper   2008-09-18 07:28:45
Gravatar image That is great! Thanks for the reply so quickly. I'll give it a shot and see how it works.
Thanks again.
Nick Cosper   2008-09-18 19:19:40
Gravatar image that worked like a charm Leif, thank you!
Jeff - new media   2008-09-26 15:26:10
Gravatar image Have you seen or would this process allow for a folder of flash video files to be randomly played?
steve   2008-12-01 21:46:06
Gravatar image first image loading is really slow. i see white, green & black screen first. then as soon i see first image it goes to second image.after that it plays fine. i think first image just stay 3 or 4 second. any clue how to fix the first image to stay 10 second?
janus   2009-02-15 18:47:17
Gravatar image hmmm ... I'm using cs3, and this doesn't seem to be working at all - could there be a flash player 10?
janus   2009-02-15 18:47:56
Gravatar image .. i mean a flash player 10 incompatibility?
Allan Browning - Slideshow   2009-03-19 23:00:01
Gravatar image This is exaclty what I need and it works well. However, I would like the images to be in a different directory than the SWF because I am placeing the SWF on a homepage and do not want all the images in the root directory. Is this possible?

Thanks,

Allan
Michael - FLA ist corrupt   2009-05-25 15:50:14
Gravatar image Hi,
i downloadet the files but the fla file is corrupt.
I can´t open it.
Chris - Unexpected File Format   2009-06-15 10:35:35
Gravatar image Can't open the source fla file with either Flash MX 2004 or Flash 8 Professional. Both say "unexpected file format".
Anonymous - re: Slideshow   2009-06-18 19:58:54
Gravatar image
Allan Browning wrote:
This is exaclty what I need and it works well. However, I would like the images to be in a different directory than the SWF because I am placeing the SWF on a homepage and do not want all the images in the root directory. Is this possible?

Thanks,

Allan

This is a great script but I'd also like to know how to direct the script to use another directory that holds the images. :)
Kylu - Another problem   2009-11-05 09:39:18
Gravatar image Hello everyone :)
The scripts work great, but I have different problem with it.

I've placed my *.swf and source.php file placed in "store/www/swf/" catalouge, and changed in AS path to file source.php.

When I play it in a simple html documment every thing seens to be fine, using the code

Quote:





the problem starts when I place it ina xhtml code below other layers (divs) :(

On the same flash movie I have a regular motion and mage rotator. The first works fine, but rotator doesn't.

Had anyone same problem ??

Best regards
Jeroen - Change size   2009-11-09 10:03:14
Gravatar image First, thanks for sharing this great bannersolution.

But how can I change the size of this? I modified the flashfile with all it's layers to my dimensions and changed the html to the right size but I get my banner at a small size surrounded by black.. Could you explain me step by step how to change the size?

Thanks in advance!
MoejS - student   2010-02-10 14:40:42
Gravatar image Hello,

Is there any one of it's possible to put the .swf in another directory and also resize the photos.

Many thx
joel   2010-02-20 23:29:02
Gravatar image This script is great, however, it only works if the html file that it is embeded into is in the same directory as all of the other files. If I have the html file outside this directory I receive: "XML file could not be found"
How would one make it work with the html file outside the directory?
Thank you.
Ben Dunkle   2010-02-22 20:51:35
Gravatar image To change the directory where the images are located, change the source.php file, line 44:

echo (' ');

to

echo (' ');

e.g., if you wanted to store the images in a folder called "images", and not have them in the same folder as the flash/php files.

Great script, it would be better if images could be centered on the stage, time could be controlled, and transitions could be controlled with built in effects rather than a hiding box. Throw in the ability to play videos as well as images and it would be perfect!
Ben Dunkle   2010-02-22 20:52:44
Gravatar image woops, code got parsed:

To change the directory where the images are located, change the source.php file, line 44:

Code:
  echo ('   ');


to

Code:
  echo ('   ');

e.g., if you wanted to store the images in a folder called "images", and not have them in the same folder as the flash/php files.

Great script, it would be better if images could be centered on the stage, time could be controlled, and transitions could be controlled with built in effects rather than a hiding box. Throw in the ability to play videos as well as images and it would be perfect!
Ben Dunkle   2010-02-22 20:53:58
Gravatar image oh well, if you take a look at line 44 you should be able to figure it out :cheer:
Juri   2010-03-25 06:14:55
Gravatar image Hello. For some reason this keeps .php code keeps giving me the same error when I try to open it in a browser (Firefox):
"This XML file does not appear to have any style information associated with it"

and in Explorer:

"A string literal was expected, but no opening quote character was found. Error processing resource 'http://www.theguliver.c...


--------------^"

Don't know what I am doing wrong. Do you have any idea at all? Cheers
Fruitbeard - differnet directory   2010-05-13 14:07:13
Gravatar image Hi there,

Thank you for the script, very useable, only one problem i have encountered, if i include the swf file from another page (includes/*.swf)
then the images do not show, do you know where I might be going wrong, it works if all files are within the same directory.

Thanx
Fruitbeard - re: differnet directory   2010-05-13 16:09:46
Gravatar image Hi,

nevermind guys, i figured it out, the xml code needs to declare the correct path, so i assigned a $variable, for the directory and placed it infront of the "'.$img.'".

Cheers
J   2010-10-01 16:00:38
Gravatar image Hi, I am using MX2004 and I've tried some AS. Tried this, the php is ok, in various browsers, but the swf produces nothing and with no apparent errors, any ideas? If my scripting was better I'd get it to spit out some data. I want it to work with another flash file that I already have in development
seotoronto - Web Development Company London   2011-08-02 04:55:56
Gravatar image I appreciate your idea here. Definitely it has a good content. This is interesting article, that is the thing I'm looking for over the net. Finally I found it. I learned a lot, this useful article and I think other readers might find it useful as well. Thank you for imparting more of your own thoughts.

http://www.seocompanylimited.ca/services.html
bil - Image size   2011-09-07 10:56:08
Gravatar image Awesome script; however, my images are 950 * 232. I have changed the size in the index.html file, but it only shows half the image and has a large black gap on the left - any ideas anyone....PLEASE !!
Tiso - Image resize solution   2011-12-16 16:59:48
Gravatar image I have a solution for the image resize:

#1 resize all layers in flash
#2 make your own index.html (and embed the SWF)

Enjoy.
maclobster - help   2011-09-19 20:54:23
Gravatar image hi i like the rotation scrip, but how do i install it, i dont understand what i download.

i work with notepad++
i work with ftp/php/html
do you have a step by step to make this work?
i have a rotation working, its include by a file called overall_header.

please help

best regards
Austin Computer Repair   2011-11-13 04:33:48
Gravatar image Good helpful post this one regarding a flash image viewer. I'm trying to create one of my own, hope it'll be a success.
Thanks
[Austin Computer Repair][/http://austinpcexperts.com]
Austin Computer Repair - Austin Computer Repair   2011-11-13 04:36:24
Gravatar image Good helpful post this one regarding a flash image viewer. I'm trying to create one of my own, hope it'll be a success.
Thanks
Marc - Wow   2012-01-09 01:45:30
Gravatar image Works woanders ty
Austin Computer repair   2012-02-05 15:48:56
Gravatar image I tried this image viewer with my new website. I am glad to find this code and their solves in the other comments.
Tennis Ladder   2012-02-05 15:49:27
Gravatar image I tried this image viewer with my new website. I am glad to find this code and their solves in the other comments.
melanie   2012-08-16 08:39:19
Gravatar image I am a web developer and yes of course we want software as dynamic as possible. This means that you can easily change the code or contents, without digging in and rebuilding your original source.
Anonymous   2012-08-22 20:54:13
Gravatar image :evil: <img src=illy:' /> :lol: :D :D :pinch: ;) :unsure:
Read more...
Name:
Email:
  Gravatar enabled.
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Security Image
Please input the anti-spam code that you can read in the image.
Unsubscribe from e-mail notifications.
 
< Prev   Next >
Subscribe

Subscribe to Marcofolio