Generating a background image from a php file - javascript

I have to generate a background image from a php file and I can't get it to work properly. Here is my situation:
I have a javascript line where I call the php file like this:
document.body.style.background = 'url(http:/...../getBackground.php) no-repeat center center fixed';
In the getBackground.php file I had to generate the background image from a folder that contains a number (that can change) of images. I did it like this:
$dir = 'images/';
$arr = scandir($dir);
$images = array();
$pattern = '([^\s]+(\.(?i)(jpg|png|gif|bmp))$)';
foreach($arr as $file){if(preg_match($pattern, $file)){$images[] = $file;}} //get only the images from the folder
$count = count($images);
$i = mt_rand(0, $count - 1); // pick a random image
header("Content-type: image/png");
$photo = 'images/' . $images[$i];
$src_img = imagecreatefrompng($photo);
imagepng($src_img);
But something is wrong because I don't get the images displayed properly. Can anyone help? What am I missing?
Thanks a lot! Cheers!

Part of the problem is you are very specifically outputting png data, but allowing jpg, png, gif and bmp source files.
This should be a LOT faster and easier on the server. This does not recreate an image each time, it just passes through the existing image.
<?php
$dir = 'images';
$ext = 'jpg,gif,png'; // List the desired image extensions here, comma separated.
$images = glob($dir.'/*.{'.$ext.'}', GLOB_BRACE);
$random = $images[array_rand($images)];
$image_type = exif_imagetype($random);
header("Content-type: " . image_type_to_mime_type($image_type));
readfile($random);
?>

Related

base64 string won't convert to image

I have the below base64 string generated from an app I'm testing out. It's supposed to generate an image but I can seem to get it to validate or display in HTML. I am trying to use PHP to decode and change to a JPG file but it seems the source of the base64 string may be the issue. Any thoughts?
I actually linked the file with the base64 in here since it's so many characters.
Thanks in advance!
PHP Code:
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
$source_type = "app";
if($pass == "Fan412") {
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../FOLDER_TO_IMAGES/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO TABLE_HERE (account, date, source_type, title, market, image) VALUES ('$account', '$date', '$source_type', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
}

Image corrupted when using Cropit and form submit

I was introduced to Cropit recently and find it really easy to use but I am stuck at one area. I am trying to use Cropit and form submit. I am following the demo provided by Cropit.
Javascript:
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
PHP:
$encoded = $base64_string;
$decoded = urldecode($encoded);
$image_name = explode(';', $decoded);
$image_name = explode(':', $image_name[0]);
$image = array_pop($image_name);
$ext = explode('/', $image);
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$str = random_string('alnum', 8);
$file = $str.'.'.$ext[1];
$data = $upload;
file_put_contents('assets/image_test/cropped/'.$file, $data);
It is able to output the file into my folder but the picture is just a blank screen with the dimension I set.
I have try to search the web but I couldn't find any solution to my problem.
Hope to get help from anyone who have encounter or know a solution.

How do I automatically display the first google image on my page?

I have a page that automatically retrieves two random entries from a MySQL database and asks the user to compare them every time the page is refreshed. How can I convert those two strings into the first google image result for them automatically? This is what I have so far:
<?php //I retrieve the names and group names here//
$firstpersonaName = (string) $row["personaName"];
$firstpersonaGroupName = (string) $row["groupName"];
$firstpersonaGroupNameForGoogle = preg_split('( )', $firstpersonaGroupName);
?> //then convert any group names containing spaces into arrays here//
<?php //then here I build the query that displays a google image page//
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
?>
This gives me stuff like: https://www.google.com/search?q=charlie+always+sunny&tbm=isch
So how do I take that link and turn it into the link of the first image? Or any of the first couple really. (In this case: http://cdn3.denofgeek.us/sites/denofgeekus/files/sunny_0.jpg)
Okay so here's what I ended up doing to randomly generate two pics per query:
First I downloaded this and added it to the same directory as the webpage: http://simplehtmldom.sourceforge.net/
Then I simply added this PHP code in the div where I wanted the picture to show up:
<?php
// Include the php dom parser
include_once 'simple_html_dom.php';
//build the google images query
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
//echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
$newname = "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
//use parser on queried page
$html = file_get_html($newname);
//echo $html;
//create an array for all pics on page
$picarray = array();
$picurl = '';
// Find all images
foreach($html->find('img') as $element) {
//echo $element->src . '<br>';
$picurl = $element->src;
array_push($picarray,$picurl);
}
//then pick two random ones
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
?>
They're pretty small resolution (about 150px) but that actually works great with what I'm trying to do. If you wanted to retrieve a non-thumbnail pic that's a whole different can of worms.

Use file_get_contents() and implode() to pass array to javascript not working

I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?

Struggling to create a php array to fetch photos from directory that can be used as an array in JavaScript

Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.

Categories

Resources