Tagged: CSS

Random Image Rotator with CSS and ASP.Net

Level: Intermediate

For my header image I have defined something in CSS like this,
#pic { BACKGROUND: url(pic.jpg) repeat-x; }.
This works fine for a static image. If you want to rotate your image, you will need to dynamically grab that image to get there. ( Google this need, and you will find a lot of pages with PHP solution ). Here is what you do in .Net to rotate images with CSS !

Your CSS file will change to reflect the ASPX page now serving the images,

#pic { BACKGROUND: url(http://localhost/imgPick/pick.aspx) repeat-x; }

And here is the code that goes to page load of pick.aspx

private void Page_Load(object sender, System.EventArgs e)
{
string imagePath = GetRandomImageFileName();
//Open the image file
System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath, true);
Graphics graphic = Graphics.FromImage(image);

//To draw some text on that image !
Font drawFont = new Font(“Arial”, 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
float x = 150.0F;
float y = 50.0F;
graphic.DrawString(“dotNetCouple :)”, drawFont, drawBrush,x,y);

//Switch page output type to “jpg”
HttpContext.Current.Response.ContentType = “image/jpg”;
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg );
//Write the image from memory to the response stream
stream.WriteTo(HttpContext.Current.Response.OutputStream);

}

private string GetRandomImageFileName()
{
Random random = new Random();
int arrIndex = random.Next(0, 2);
//I have an array of 3 images here!
//change this routine to your suite your needs !
string[] imgNames = new string[]
{
@”c:\binu\html\css\pic.jpg”,
@”c:\binu\html\css\pic1.jpg”,
@”c:\binu\html\css\pic2.jpg”
};
return (imgNames[arrIndex]);

}

and your HTML could look like this,

Some Text, This text will still be shown if there is no image served !

 

put all these together, and there you have it, a CSS based image rotator.