Greetings,
I am adding four random photos from a featured photo album to the front page of a site in the form of a jQuery photo slider. Since all of the images must be the same size, I select only horizontal photos, shuffle them, and then trim that down to 4. Here is the code I am using. My question - is there a simpler, perhaps more efficient way to do this? Or is my method fairly sound?
Thanks!
$getImages = $gallery_db->query("SELECT * FROM images WHERE album = '5'"); //sample SQL
$imagesArr = array();
while ($image = $getImages->fetch()) {
$path = "http://somewhere.com/gallery/photos/" .
$image['album'] . "/" . $image['filename'] . ".jpg"; //All files are .jpg
list ($width, $height) = getimagesize($path);
if ($width > $height) {
$imagesArr[] = $path;
}
}
shuffle($imagesArr);
array_splice($imagesArr, 4)
and then, to output:
foreach ($imagesArr as $path) {
echo "<img src=\"$path\" width=\"220\" height=\"110\"/><br/>\n";
}
Your solution looks just fine, it's pretty simple and straight forward. But remember, premature optimization is the root of all evil :)
A improvement would be to store the dimensions of each image in your database, so that you can fetch all images of a certain size and just take 4 random images.
Related
I've put together some code to search through a directory and for all the jpg images it finds, display thumbnails and my required iptc and exif info.
The problem is that I have many, many directories of photos and as it is I need an index.php file for each one.
My directories are named by month and year; "1401" for January 20014, "1402" for Feb etc. and I have a set of shortcut images for each one called "1401.jpg", "1402.jpg" etc.
so I use this code for users to nagivate to other directories where $shortcut has the values of 1401, 1402 etc:
echo("<img src=\"shortcutimages/" . $shortcut . "\">");
I'd love to allow users to navigate in a similar way without needing multiple index.php files.
I would guess the best way is as follows:
On a mouseclick on a link like above, the main php (similar to below) should be re-run, replacing what's currently displayed on the screen but with new value for $dir replaced with something like $dir="../" . $shortcut;
Is this the way to do it? As a newbie I apologise if this is really simple but as it is I can't seem to work it out.
thanks in advance for your help,
Sivadas
$dir="."; // or other folder path of choice!
$jpgcount=0;
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($image = readdir($dh)) !== false)
{
if (preg_match("/.jpg/", $image)) // only use .jpg files
{
$image=$dir . "/" . $image;
$exif = exif_read_data($image, 0, true);
$exif_name = $exif['FILE']['FileName'];
if(isset($exif['EXIF']['DateTimeOriginal']))
{
$timestamp = $exif['EXIF']['DateTimeOriginal'];
}
else
{
$timestamp = "1971:01:01 01:01:01"; // puts in a datestamp if one doesnt exist
}
$datename[] = $timestamp . $exif_name; // create array of date+name to allow sorting by date then retrieval of date ordered names once datestamp is removed
$jpgcount++; // counts number of jpgs in folder
}
}
sort($datename); // sort date+name array by date
for($c=0; $c<$jpgcount; $c++)
{
$image = pythonslice("$datename[$c]","19:"); // function strips off the datestamp (1st 19 characters) to leave the filename (taken from www.php.net/manual/en/function.substr.php slow at acedsl dot com)
$image=$dir . "/" . $image;
$size = getimagesize("$image", $info);
echo("<tr><td valign=top> <IMG border=0 src=showthumb.php?image=" . str_replace(' ', '%20', $image) ."><td><td valign=top><font size=-1 face=\"Arial Narrow\">"); // get thumbnail and link to full image
show_metadata($image,$info); // function to display all required metadata
echo "</font></td></tr>";
}
closedir($dh);
}
}
First question, so sorry if I do something wrong!
My issue is, I have a product catalog, which displays up to 18 thumbnails, each approx 6kb, in a product catalog. Each of the thumbnails calls a script get_db_image which searches for and returns the image relating to the product. Simple, so far. The issue only arises when approx 3 or 4 requests are made at the same time for a product catalog page, each user is expecting 18 thumbnails and details to be returned, but when they all do it at the same time I get out of memory errors and sometimes the server crashes. I've stripped down the code that retrieves and displays the image, and the hosting people have raised the memory limit to 256M, but it's all to no avail. As far as I can tell I'm destroying the images I've created and the virtual memory goes back to zero split seconds after the requests are made, but at the peak all the memory is being utilised, hence the crashes, so the only thing I can think off doing is getting, displaying and destroying each image before I start the next one, but I don't know how to go about that, but maybe there is a better solution? Please help, pulling my hair out and I don't have a lot to waste!
// executes the query searching for the image
$res = execPDORetRes($query, $vars);
// if there is no image, load a default
if(sizeof($res) == 0)
{
$query_parts = explode(" ", $query);
$query = "select * from ".$query_parts[3]." where id = :id";
$vars = array(':id-int' => 1);
$res = execPDORetRes($query, $vars);
}
$data = $res[0];
// create the image from the DB
$img = imagecreatefromstring($data[$name]);
$type = "image/pjpeg";
Header( "Content-type: image/pjpeg");
$width = imagesx($img);
$height = imagesy($img);
// if the image is too big
if($size_w != $width || $size_h != $height)
{
// set widths and heights
if ($width <= $size_w)
{
$new_w = $width;
$new_h = $height;
}
else
{
$new_w = $size_w;
$new_h = $size_h;
}
// create a new image of the specified width and height
$new_img = imagecreatetruecolor($new_w,$new_h);
// resize the original
imagecopyresized($new_img,$img,0,0,0,0,$new_w,$new_h,$width,$height);
// determine image type and send it to the client
imagejpeg($new_img,"","80");
// clear the image from memory
imagedestroy($new_img);
imagedestroy($img);
unset($width, $height, $new_h, $new_w, $new_img, $img);
}
else
{
// if the image is smaller than or the right size
// determine image type and send it to the client
imagejpeg($img,"","80");
// clear the image from memory
imagedestroy($img);
unset($width, $height, $img);
}
ob_flush();
Thanks for the help.
I think you should generate your thumbnails in advance if you want to this it this way.
This means you should have your normal product images under e.g. "public/images/products/main" and then your thumbs under "public/images/products/thumbs" and then store in the database your paths to the product images and your thumbs.
This approach is better then creating them on the fly.
Otherwise you could just scale them down with css, if bandwidth is not a problem, but I guess it is.
You can even keep your thumbs script and check in the db if a thumbnail exists, if it does not, call your script: generate thumb, save thumb, update db. The next time a user comes and you need to display this thumbnail, it will already be there.
256 megabytes should be plenty. Nothing in your code looks bad and you're even using unset. I recommend debugging with Xdebug and WinCacheGrind, they can produce in-depth logs...
My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>
I want to do a picture search engine. I use simple_html_dom and preg_match_all to get all the images, then use getimagesize to get all the image sizes.
Here is one part of my code.
<?php
header('Content-type:text/html; charset=utf-8');
require_once 'simple_html_dom.php';
$v = 'http://www.jqueryimage.com/';
$html = file_get_html($v);
foreach($html->find('img') as $element) {
if( preg_match('#^http:\/\/(.*)\.(jpg|gif|png)$#i',$element->src)){
$image = $element->src;
//$arr = getimagesize($image); //get image width and height
//$imagesize = $arr[0] * $arr[1];
echo $image.'<hr />';
}
}
?>
First question, how to add a judgement so that I can echo the biggest size image? (only one image).
Second question, I can get the image real url in these two possibilities, first where image is as a 'http' began, second where image is as a / began.
But how to get the image real url in the situation where image is as a './' or ../ or ../../ began? it is difficulty for me to judge how many ../ in a image, then cut the site url to complement a image real url?
Thanks.
Insert this before foreach loop:
$maxsize = -1;
$the_biggest_image = false;
Insert this below $image = $element->src; line
$arr = getimagesize($image);
if (($arr[0] * $arr[1]) > $maxsize) {
$maxsize = $arr[0] * $arr[1];
$the_biggest_image = $image;
}
After foreach loop you'll have $the_biggest_image variable set or false if nothing found. This will take first one if more than one 'biggest image' found.
For second question, I don't know!
Edit: fixed something!
My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.
Appreciate your help
Thank you.
I don't know whats about the $img_id but you could consider to use shuffle().
shuffle($file_array);
But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:
$file_array = array(
array("images/bag200.bmp", 1),
array("images/bag178.bmp", 1),
array("images/bag004.bmp", 0,
...
);
In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)
You can loop over images this way (they are in random order now):
<?php foreach($file_array as $image): ?>
<img src="<?php echo $image ?>" />
<?php endforeach; ?>
If you only want to display a subset of the images, randomly chosen, you can do this:
$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly
shuffle($rand); //shuffle keys
foreach($rand as $r) {
echo '<img src="' . $file_array[$r] . '" />';
}
Some comments on your code:
$ran = array_rand($file_array);
$ran contains a key randomly chosen from the images.
for ($i=0;$i<200;$i++) {
//while (in_array($tst,$rand_array)){
$tst = $file_array[$ran];
$id = $img_id[$ran];//}
$rand_array[] = $tst;
$rand_id[] = $id;
}
You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.
If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html