I'm just learning php and am stuck on a basic problem. I'd like my site to display one of ten random images (1.png ... 10.png) if a user doesn't choose an image. Currently it just displays a single image by default. There is a thumbnail and full size version of this image.
I've found the file where this is controlled is:
<?php
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$file = $small ? 'no_image_small.png' : 'no_image.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
I've tried to replace 'no_image_small.png' with the names of my images typed out in quotes ('1.png', '2.png',...). Other answers I've seen on stackoverflow are a little too advanced for me to apply as I don't know where to add arrays for both the 'no_image_small.png' and 'no_image.png'.
Thanks very much
I'm not sure what framework you are using, what classes are extended, but try this:
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$random = rand(1, 10);
$file = $small ? $random.'_small.png' : $random.'.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
This assumes, that the images "1.png".."10.png" and "1_small.png".."10_small.png" are located in the same directory, where no_image_small.png and no_image.png are stored.
For example:
$random = rand(1, 10); // generating random number and saving to $random variable
echo $random.'.png'; // concatenating random number to .png extension
Outputs:
8.png
or any other from 1 to 10
This should set $file variable with the correct image.
Reference: rand
Try using php rand()
You can use rand(1,10) this means echo out a random numbers from 1 to 10.
like for example: echo rand(1,10)."jpg";
Related
I am using array_walk in a script where I can call one specific function; now, I would like to call a function randomly from a pool of similar functions and manipulate the array values. It could be a loop construct. To be more specific, they are all image functions, generating images dynamically. Another requirement is that I need to save images in a particular order in a folder such as 001.jpg, 002.jpg, 003.jpg and so on. Currently, I am saving images using the code imagejpeg($im, "savedimages/" . time() . "-" . rand() . ".jpg", 90); As I call a function randomly, is it possible to maintain a similar order in saving images. I need an idea how to do that.
$fontFace = 'AmsiPro-Ultra.ttf';
$sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $html);
array_walk($sentences, 'dynamicImage', $fontFace);
function dynamicImage($sentence, $key, $fontFace)
{
$img = 'green.jpg';
$client = new Client;
$image = $client->loadJpeg($img);
$palette = $image->extract();
imagickResize($img);
// create a transparent base image that we will merge the square image into.
$img = new Img();
$img->create(640, 720, true);
// first image; merge with base.
$img2 = new Img('small_square_img.jpg');
$img->merge($img2);
$img->save();
$color = 'D2F57D';
pngcolorizealpha('second_img.png', $color);
stringFunction($sentence, $palette[0], $fontFace);
$im = mergeImages(array(
'first.image.jpg',
'second.image.jpg'
));
# header('Content-type: image/jpg');
imagejpeg($im, "savedimages/" . time() . "-" . rand() . ".jpg", 90);
}
something like this
$func_1 = function(){
echo '1';
};
$func_2 = function(){
echo '2';
};
$functions = array(
$func_1,
$func_2,
..
);
array_shuffle( $functions );
$functions[1]( );
or
foreach( $functions as $index => $function ){
$function();
}
On the last one array_shuffle, if I remember right will reset the keys, if not you can do array_values($functions ) to reset them. Also note I've not tested this, but essentially that should work.
I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.
I want to rotate an uploaded and retrieved image from one location. Yes i am almost done. But the problem is, due to header("content-type: image/jpeg") the page redirected to another/or image format. I want to display it in same page as original image in. Here my code..
$imgnames="upload/".$_SESSION["img"];
header("content-type: image/jpeg");
$source=imagecreatefromjpeg($imgnames);
$rotate=imagerotate($source,$degree,0);
imagejpeg($rotate);
i also did with css property.
echo "<img src='$imgnames' style='image-orientation:".$degree."deg;' />";
But anyway my task is to done only with php. Please guide me, or give any reference you have
thanks advance.
<?php
// Okay, so in your upload page
$imgName = "upload/".$_SESSION["img"];
$source=imagecreatefromjpeg($imgName);
$rotate=imagerotate($source, $degree,0);
// you generate a PHP uniqid,
$uniqid = uniqid();
// and use it to store the image
$rotImage = "upload/".$uniqid.".jpg";
// using imagejpeg to save to a file;
imagejpeg($rotate, $rotImage, $quality = 75);
// then just output a html containing ` <img src="UniqueId.000.jpg" />`
// and another img tag with the other file.
print <<<IMAGES
<img src="$imgName" />
<img src="$rotName" />
IMAGES;
// The browser will do the rest.
?>
UPDATE
Actually, while uniqid() usually works, we want to use uniqid() to create a file. That's a specialized usage for which there exists a better function, tempnam().
Yet, tempnam() does not allow a custom extension to be specified, and many browsers would balk at downloading a JPEG file called "foo" instead of "foo.jpg".
To be more sure that there will not be two identical unique names we can use
$uniqid = uniqid('', true);
adding the "true" parameter to have a longer name with more entropy.
Otherwise we need a more flexible function that will check if a unique name already exists and, if so, generate another: instead of
$uniqid = uniqid();
$rotImage = "upload/".$uniqid.".jpg";
we use
$rotImage = uniqueFile("upload/*.jpg");
where uniqueFile() is
function uniqueFile($template, $more = false) {
for ($retries = 0; $retries < 3; $retries++) {
$testfile = preg_replace_callback(
'#\\*#', // replace asterisks
function() use($more) {
return uniqid('', $more); // with unique strings
},
$template // throughout the template
);
if (file_exists($testfile)) {
continue;
}
// We don't want to return a filename if it has few chances of being usable
if (!is_writeable($dir = dirname($testfile))) {
trigger_error("Cannot create unique files in {$dir}", E_USER_ERROR);
}
return $testfile;
}
// If it doesn't work after three retries, something is seriously broken.
trigger_error("Cannot create unique file {$template}", E_USER_ERROR);
}
You need to generate the image separately - something like <img src="path/to/image.php?id=123">. Trying to use it as a variable like that isn't going to work.
I'm trying to get a webpage to show images but it doesn't seem to be working.
here's the code:
<?php
$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" alt="random image">'." ";
}
?>
If the code should work, where do i put it?
If not, is there a better way to do this?
You'd need to put this code in a directory that contains a directory named "images". The directory named "images" also needs to have files in a *.* name format. There are definitely better ways to do what you're trying to do. Such would be using a database that contains all the images that you want to display.
If that doesn't suit what you want to do, you'd have to be much more descriptive. I have no idea what you want to do and all I'm getting from the code you showed us is to render every file in a directory called "images" as an image.
However, if this point of this post was to simply ask "How do I execute PHP?", please do some searching and never bother us with a question like that.
Another thing #zerkms noticed was that your for .. loop starts at iteration 1 ($i = 1). This means that a result in the array will be skipped over.
for ($i = 0; $i < count($files); $i++) {
This code snippet iterates over the files in the directory images/ and echos their filenames wrapped in <img> tags. Wouldn't you put it where you want the images?
This would go into a PHP file (images.php for example) in the parent directory of the images folder you are listing the images from. You can also simplify your loop (and correct it, since array indexes should start at 0, not 1) by using the following syntax:
<?php
foreach (glob("images/*.*") as $file){
echo '<img src="'.$file.'" alt="random image"> ';
}
?>
/**
* Lists images in any folder as long as it's inside your $_SERVER["DOCUMENT_ROOT"].
* If it's outside, it's not accessible.
* Returns false and warning or array() like this:
*
* <code>
* array('/relative/image/path' => '/absolute/image/path');
* </code>
*
* #param string $Path
* #return array/bool
*/
function ListImageAnywhere($Path){
// $Path must be a string.
if(!is_string($Path) or !strlen($Path = trim($Path))){
trigger_error('$Path must be a non-empty trimmed string.', E_USER_WARNING);
return false;
}
// If $Path is file but not folder, get the dirname().
if(is_file($Path) and !is_dir($Path)){
$Path = dirname($Path);
}
// $Path must be a folder.
if(!is_dir($Path)){
trigger_error('$Path folder does not exist.', E_USER_WARNING);
return false;
}
// Get the Real path to make sure they are Parent and Child.
$Path = realpath($Path);
$DocumentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// $Path must be inside $DocumentRoot to make your images accessible.
if(strpos($Path, $DocumentRoot) !== 0){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// Get the Relative URI of the $Path base like: /image
$RelativePath = substr($Path, strlen($DocumentRoot));
if(empty($RelativePath)){
// If empty $DocumentRoot === $Path so / will suffice
$RelativePath = DIRECTORY_SEPARATOR;
}
// Make sure path starts with / to avoid partial comparison of non-suffixed folder names
if($RelativePath{0} != DIRECTORY_SEPARATOR){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// replace \ with / in relative URI (Windows)
$RelativePath = str_replace('\\', '/', $RelativePath);
// List files in folder
$Files = glob($Path . DIRECTORY_SEPARATOR . '*.*');
// Keep images (change as you wish)
$Files = preg_grep('~\\.(jpe?g|png|gif)$~i', $Files);
// Make sure these are files and not folders named like images
$Files = array_filter($Files, 'is_file');
// No images found?!
if(empty($Files)){
return array(); // Empty array() is still a success
}
// Prepare images container
$Images = array();
// Loop paths and build Relative URIs
foreach($Files as $File){
$Images[$RelativePath.'/'.basename($File)] = $File;
}
// Done :)
return $Images; // Easy-peasy, general solution!
}
// SAMPLE CODE COMES HERE
// If we have images...
if($Images = ListImageAnywhere(__FILE__)){ // <- works with __DIR__ or __FILE__
// ... loop them...
foreach($Images as $Relative => $Absolute){
// ... and print IMG tags.
echo '<img src="', $Relative, '" >', PHP_EOL;
}
}elseif($Images === false){
// Error
}else{
// No error but no images
}
Try this on for size. Comments are self explanatory.
I have nearly 1 million photos auto-incremented starting at "1".
So, I have the following:
1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
....
1000000.jpg
Currently, I have all of these files in a single Ext4 linux directory.
As you can imagine, the filesystem is crazy slow.
Using PHP, how can I create an algorithm that divides up my images into a directory structure so that each directly has significantly less objects per directory.
For example:
1000/1.jpg
1000/2.jpg
1000/3.jpg
...
1000/999.jpg
1000/1000.jpg
2000/1001.jpg
2000/1002.jpg
2000/1003.jpg
2000/1999.jpg
How would I divide/modulus/implode/shift the image name (id) into a file structure like such above?
UPDATE:
Basically, I want to create a PHP function that does the following.
Only accept positive integers, not including 0.
For values 1-999, return 0
For values 1000-1999, return 1000
For values 10,000-10,999, return 10000
For values 25,000-25,999, return 25000
When I've done things like this in the past, I create subdirectories from the rightmost digits, so that as they increment, they are added to all the directories more evenly:
4/3/1234.jpg
5/3/1235.jpg
6/3/1236.jpg
7/3/1237.jpg
8/3/1238.jpg
Re your comment:
how would I do that with PHP?
Here's an example function in PHP:
function NumToPath($n)
{
$n = (int) $n;
if ($n <= 0) {
return false;
}
$n = str_pad($n, 7, "0", STR_PAD_LEFT);
preg_match("/.*(\d)(\d)$/", $n, $matches);
$path = $matches[2] . "/" . $matches[1] . "/" . $n . ".jpg";
return $path;
}
You should keep the current (incrementing) number in a meta-file, so that you can retrieve it very quickly. Everything else is pretty easy:
$directory = ceil($num / 1000) * 1000;
$filename = $num . '.jpg';
$path = $directory . '/' . $filename;
i guess you think far to complex.
untested very basic way of doing this:
for($i=0;$i<1000000;$i++){
if(file_exists($i.'.jpg'){
$multi = floor($i/1000);
$dir = ($multi <= 1) $dir = 1000 : $dir=$multi*1000;
if(!is_dir($dir)){
mk_dir($dir);
}
move($i.'.jpg',$dir.'/'.$i.'.jpg);
}
}
Untested but should work. Certainly back up your stuff first or try it on just a small sample directory.
<?php
// specify your image directory, no trailing slash
$imagedir = 'your/path/to/images';
// loop through each jpg file in the image directory
foreach (glob($imagedir.'/*.jpg') as $file)
{
// determine new folder name
$newdir = floor(basename($file) / 1000) * 1000;
// ^ php will interpret the filename's number for the calculation
// eg: ('999.jpg' / 1000) returns .999
// ensure the 0 folder name is not null
if (!$newdir) {
$newdir = '0';
}
// add the new folder to the image directory
$newdir = $imagedir.'/'.$newdir;
if (!is_dir($newdir)) {
mkdir($newdir);
}
// move the image
rename($file, $newdir.'/'.basename($file);
}
?>