Send Dynamically generated Image in Javascript as Image Header in PHP - php

What I am doing
Generating a dynamic image via javascript based on some variables specified in the query string. I am using this in a PHP Website.
What I need
The point here is I want to send this dynamically generated image in javascript to be displayed on the page as Image Header.
What I am using
PHP with APACHE Server (wamp)
Similar example of what I require
http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World
This is a Google Chart API, upon hitting the above URL, it returns you a PNG image based on the parameters specified in the Query String.
I have tried a lot, but yet unable to reach the success point.
Just, to show you what I am doing here is the Code
My Code Portion
/*
Logic to generate a canvas based on some parameters goes here
*/
// Canvas to Image
var img = canvas.toDataURL("image/png");
/*
My goal is to set this image to header of the page,
so that when the page is hit, an image is returned,
just like the Google Chart API thing mentioned above
*/

Create a javascript variable like this:
var monthly ="value to pass";
var recent ="value to pass";
var imgURL="http://YOURSITEURL/FOLDER/app1?monthly="+monthly+"&recent="+recent+"&likes="+likes;
Or:
var image = document.createElement("img");
image.src ="http://117.204.247.139:8084/myapps/app?monthly="+monthly+"&recent="+recent+"&likes="+likes;

I am not completely sure If I understand what you want. But on the PHP side you can
generate a PNG or JPEG file with a library like GD or Imagemagick.
(http://php.net/manual/en/book.image.php)
You can then send the data back to the client by setting the correct header, for PNG:
<?php
header("Content-Type: image/png");
ob_start();
echo $pngdata; // the binary data
ob_end_flush();

Related

Use qrencode to generate png/svg QR code for Wireguard client configuration

I am looking to generate a QR code on a PHP webpage. The user starts on a page where they submit a form, the only input being the name of the new client. This page is a manager for VPN clients.
After the redirect, PHP generates the configuration file on the page to copy and paste. The user must save this file as wg.conf in their etc directory. I have been trying to use qrencode, a Linux based command line tool to generate the QR code on that same page with the configuration file. According to the documentation on qrencode, you can save the file as a .png or .svg.
I have been playing around with it, both trying to pass data through the URL as GET parameters in the redirect (the only issue is the QR code is sensitive) and by using the backtick operators to run bash commands to save it as a file in the user's local files. I can't seem to figure out where to save it as a file or whether there's another solution to display it on the webpage.
how i would do it:
check this library https://github.com/neocotic/qrious , all you need to do it load the js on your page
generate text you want to convert to qr code in a text area, div or other HTML element and assign it an id
use that id to extract the data via pure JS, now you have a text variable and you have the possibility to make qr code dynamic now
once you have the data dynamically extracted via JS you can use that variable to generate qr codes like this :
var x = 'sample text'
var qr = window.qr = new QRious({
element: document.getElementById('qrious'),
size: 200,
value: x
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
<canvas id="qrious">

how to read image file as data url using php

In javascript, I read the file data by binding the on-change method to the file input and saving the file data into another input using the following code
$("#release_cover_custom").on('change', function (evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
$("#release_cover_custom_data").val(e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
why i use the above code?, to store the image data, because i have a form where i provide settings for the email template that would be sent later and there i have to provide the background image to be used inside the email, i need to preview the email with all the settings and along with the background image provided to upload before saving the form or uploading the image, so i read the image data, save it to an input and then open a modal window to preview email and post all the necessary variables there including the image data which is then used in the following way inside the css to apply the background-image like below in my php view file
background-image:url('" . $background_image . "') !important;
Now i want to do the achieve the same thing via php, means if i have the image saved to a path and i want to read the image data and use it in the same way i did using javascript to futher pass it to the css property,
i tried to use base64_encode(file_get_contents('path/to/file'))
but the encoding seems to be different for the image data, as the background image is not shown should i be using some other method to achieve it in php.
#quagaar reply (on the question) helped me solve the problem and replaced the following
$background_image=base64_encode(file_get_contents('/path/to/file'));
with
$background_image='data:image/png;base64,'.base64_encode(file_get_contents('/path/to/file'));
and everything works fine as expected.
EDIT:
between i was dealing with images only and if you are working with Images only and you need mime type (e.g. for headers, or like my case), then this is a fast and reliable technique:
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
It will output true image mime type even if you rename your image file.

How to treat a PHP image generation script as an image

This is an odd question but I'm stuck on how I would achieve this and I am unable to find any methods of doing so.
I have a simple php script that takes variables (containing file names) from the URL, cleans then and then uses them to generate a single image from the inputted values. This works fine and outputs a new png to the webpage using:
imagepng($img);
I also have a facebook sharing script in PHP that takes a filepath as an input and then shares the image on the users feed where this statement is used to define the image variable:
$photo = './mypic.png'; // Path to the photo on the local filesystem
I don't know how I can link these two together though. I would like to use my generation script as the image to share.
Can anyone point me in the right direction of how to do this? I am not the master of PHP so go easy please.
-Tim
UPDATE
If it helps, here are the links to the two pages on my website containing the outputs. They are very ruff mind you:
The php script generating the image:
http://the8bitman.herobo.com/Download/download.php?face=a.png&color=b.png&hat=c.png
The html page with the img tag:
http://the8bitman.herobo.com/Share.html
Treat it as a simple image:
<img src="http://yourserve/yourscript.php?onlyImage=1" />
yourscript.php
if($_GET['onlyimage']) {
header('Content-type:image/png'); //or your image content type
//print only image
} else {
//print image and text too
}

how to send png image from server to display in browser via ajax

I have been having a hard time with what must be an incredibly normal task. I upload and save images to my web server and save the path to the file in MySQL data base (this is all working). The thing that doesn't work is fetching an image file from the server and displaying it on the page via ajax.
Originally I was trying to just retrieve the path from the database, and update an tag's src attribute with the path to the image. This was working, but this way all the images are in a folder on the server where people all have access to them. This is not good. I can only have the pictures that belong to certain users accessible by these users.
In order to restrict access to these photos I added an Apache directive on that folder, which successfully restricted access. The problem then became that I could not display the images in the browser by setting the src attribute to that path. See my post: https://serverfault.com/questions/425974/apache-deny-access-to-images-folder-but-still-able-to-display-via-img-on-site
Finally I have learned that I have to use PHP to read the image data directly from the server and send this data to the browser. I have used the file_get_contents() function, which works to convert the image file (PNG) on the server into a string. I return this string to the browser in an ajax call. The thing I can't get is: how to convert this string back into an image using JavaScript?
See this code:
$.ajax({
url: get_image.php,
success: function(image_string){
//how to load this image string from file_get_contents to the browser??
}
});
You could display a default "no access" image to users who are forbidden to access the image:
<?php
$file = $_GET['file']; // don't forget to sanitize this!
header('Content-type: image/png');
if (user_is_allowed_to_access($file)) {
readfile($file);
}
else {
readfile('some/default/file.png');
}
And, on the client side:
<img src="script.php?file=path/to/file.png" />
Alternatively, if you really really want or need to send the data via Ajax, you can Base64 encode it:
<?php
echo base64_encode(file_get_contents($file));
And place the response in an img tag using the Data URI scheme
var img = '<img src="data:image/png;base64,'+ server_reponse +'"/>';
Given that the Base64 encoded data is significantly larger than the original, you could send the raw data and encode it in the browser using a library.
Does that make sense to you?
Instead of getting get_image.php through AJAX, why not just use:
<img src="get_image.php" />
It's practically the same thing. You can just use AJAX to update the <img> dynamically.
You can't do it via ajax.
You could do something like this:
<img src="script.php?image=image_name" />
Then use JavaScript to change the query string.
You can actually embed image data inside the img tag in the browser, therefore ajax code could look like this:
$.ajax({
url: get_image.php,
success: function(image_string){
$(document.body).append("<img src='data:image/gif;base64," + base64_encode(image_string) + "' />);
}
});
Note that you will need to write this base64_encode function. Have a look at this question - the function is given there.

AS3 Load PNG from PHP

I need some help with loading a PNG file from a server into my flash project. What I want to do it be able to call a PHP page and send it a variable which I can do. Then I want to access a db and get a path for the image, I can do this too. What I'm not sure about is what to do then.
What I need to happen is the PHP to return the PNG to flash somehow. Can I just add the PNG to the php page and use a loader somehow? I've been searching around google but most tutorials seem to be getting PNGs out.
Thanks
Ben
It is actually pretty easy. : )
<?php
// do some mysql magic.
// let's assume you get a filename back as $file_name;
header('Content-type: image/png');
readfile($file_name);
Note that you may have to include some path info as well. Not sure where your images are stored, but if the image are in /var/www/public/images, you'd wany to prepend that into your file_get_contents call.
Added: also, if you just want to return a path to the PNG, you can do a URLRequest to a PHP file, let it figure out where the image lives, and return a URL. This is even easier... I'd just recommend standardizing on a data interchange protocol like XML or (even better) JSON... that way, if you ever decide that you want to break out of Flash and into browser technologies, your backend will already be waiting for you.
<?php
// do some mysql magic.
// let's assume you get a filename back as $file_name;
$retVal = array('pathname'=>$file_name);
header('Content-type: application/json');
echo json_encode($retVal);
if you can just return the url to the flash it will be sufficient.
import flash.display.*;
import flash.net.URLRequest;
var rect:Shape = new Shape();
rect.graphics.beginFill(0xFFFFFF);
rect.graphics.drawRect(0, 0, 100, 100);
rect.graphics.endFill();
addChild(rect);
var ldr:Loader = new Loader();
ldr.mask = rect;
var url:String = ""; //put the returned img url you got from the php here.
var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq); //the loader will start loading the img
addChild(ldr); //here you add the loader to stage.
maybe for a millisec or two you just see nothing. But as soon as the loader has loaded the img you will see it.
You must input the returned img url. So not the url to the webpage that returns the img url.
If you combine the above with the answer of John Green - PageSpike you can use my code as long as the php page is that of the one in John Green - PageSpike his answer and you pass instead of the returned img then pass the url to the php page with parameter;
var url:String = "http://www.yoursite.com/getImage.php?imgParameter=image123";
So the url is now the link to the script of John Green - PageSpike which will return infact the image.
As Jhon Green has mentioned, it will work
http://www.yourserver.com/filesforflash/?file_id={id}
header('Content-type: image/png');
readfile($file_name);
but some times you may need also need the above url will not work even if you send headers of content type image/png. Quick tip for that is to send file name itself instead if its id
http://www.yourserver.com/filesforflash/{id}-filename.png
For this you may need to use mod-rewrite.

Categories