0
This class written in PHP is very useful when you want to display random images in your website. I’ve used this class to generate the Homepage image for an image gallery website. Because the homepage requires the image to be large and must follows specific width to caters the design, in this example 800px, then the class will need to have the following method:
Get random row from uploaded images > get the filename and caption> check the file’s width > call the class from the design area.
The PHP class:
<?PHP
class getRandomImage {
public $file;
public $caption;
function checkWidth($file){
list($width, $height, $type, $attr) = getimagesize($file);
if ($width>=800){ //image's width must be at least 800px
return true;
}
return false;
}
public function getImage(){
$uploadpath = 'images/gallery/'; //path of uploaded images
$width = 0;//Get random row from the MySql database
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `gallery_image` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `gallery_image` LIMIT $offset, 1 " );
$row=mysql_fetch_object($result);
if(mysql_num_rows($result)>0){
$file=$row->filename;
$caption=$row->caption;
$this->setCaption($row->caption); //set caption
$file=$uploadpath."".$file;
if (!$this->checkWidth($file)){ //if width not satisfied, get another row
return $this->getImage();
}
}
return $file;
}
//getters
public function getCaption() {
return $this->caption;
}
//setters
public function setCaption($caption) {
$this->caption = $caption;
}
}
?>
Then call the method from where you want to place the image. Here I will set the image as the DIV background.
<?PHP
$getRandomImage = new getRandomImage;
?>
<div class="mainImage" style="background:url(<? echo $getRandomImage->getImage(); ?>)">
<?PHP
//get caption
if($getRandomImage->getCaption()!=''){
echo "<div class=\"caption\">".$getRandomImage->getCaption()."</div>";
}
?>
</div>
Thats it. If you have a better suggestion or cought a bug, please comment :)
