How to display a random image in ASP

Jump to menu

26 October 2003

  1. Take images, all of which have the same extension. Put them in a single directory.

  2. Number them. Not in your head, on the server. You can pad with zeroes, but they must be numbered 1 to n, where n is the total number of images.

  3. Copy the following into default.asp, index.asp, or whatever your default document is.

    <%@
    Language           = VBScript
    EnableSessionState = False
    %>
    <%
    Option Explicit
    Dim Images Padding, Extension, Image
    Images    = 24
    Padding   = 3
    Extension = "jpg"
    Randomize
    Image = CStr(CInt(Rnd() * Images) + 1)
    If Padding > 0 Then Image = Replace(Space(Padding - Len(Image)), " ", "0") & Image
    Response.Redirect(Image & "." & Extension)
    %>
    
  4. Set Images to the total number of images, Padding to the number of digits in each filename (for 001.jpg…999.jpg, this is 3), and Extension to the common file extension.

  5. That’s it. Bearing in mind that the above code is more verbose than it needs to be. How worthy of an article is this, would you say? What about a fucking huge revision history, pointless ‘features’ , and a copyright notice?

I’m not in a very good mood today.