Reputation: 307
I'm currently using this php code to to display images on php page with some text which is given by the user using input tag.
My php code is:
<?php
header('Content-type: image/jpeg');
$jpg_image = imagecreatefromjpeg('img/1.jpg');
$white = imagecolorallocate($jpg_image, 73, 41, 236);
$font_path = 'OpenSans-Italic.TTF';
$text= $_GET['name'];
imagettftext($jpg_image, 25, 0, 75, 50, $white, $font_path, $text);
imagejpeg($jpg_image);
imagedestroy($jpg_image);
?>
This code is perfectly working I'm using $_GET['name'];
to take input from the user as you can see I have selected a picture on which my text given by the user will appear any my image name is 1.jpg
I have more pictures in my library which I want that they should be selected randomly and print text on them given by the user my other pictures name are 2.jpg
,3.jpg
,4.jpg
hope you will find any solution for me.
Upvotes: 3
Views: 629
Reputation: 106
The other answers assume you always use numeric values for filenames but if you don't you could put the filenames in an array and use array_rand()
to get a random filename from the array like this:
$image_files = array("1.jpg", "2.jpg", "3.jpg", "4.jpg");
$image_filename = $image_files[array_rand($image_files)];
$jpg_image = imagecreatefromjpeg("img/{$image_filename}");
Remember that array_rand()
returns a random key from an array, not a value.
From here you could easily take it a step further and use glob()
to get your filenames from a directory. When doing this you should take into account that glob()
returns full paths so you will need to use basename()
to get just the filename:
$image_files = glob("img/*.jpg");
$image_path = $image_files[array_rand($image_files)];
$image_filename = basename($image_path);
Upvotes: 2
Reputation: 1663
$countImages = 10; // your last number
$jpg_image = imagecreatefromjpeg('img/' . rand(1,$countImages). '.jpg');
Upvotes: 0
Reputation: 3561
Assuming you have 15 images, you can use:
$randomNumber = rand(1, 15);
$jpg_image = imagecreatefromjpeg('img/' . $randomNumber . '.jpg');
Upvotes: 2