I want to take the image data from my canvas on the client and save it as a .png on my server.
This is the code on my client that gets the image data from the canvas and sends it to saveImage.php:
function render()
{
var imageData = ctx.canvas.toDataURL("image/png");
var postData = "imageData="+imageData;
var ajax = new XMLHttpRequest();
ajax.open("POST","saveImage.php",true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.onreadystatechange=function()
{
console.log(ajax.responseText);
}
ajax.send(postData);
}
And this is what saveImage.php looks like:
<?php
if(isset($_POST["imageData"]))
{
$imageEncoded = $_POST["imageData"];
$imageDataExploded = explode(',', $imageEncoded);
$imageDecoded = base64_decode($imageDataExploded[1]);
$filename = time()."image".mt_rand();
$file = fopen("./".$filename.".png","wb");
fwrite($file, $imageDecoded);
fclose($file);
echo $filename;
exit();
}
?>
The code actually works fine, my problem is just that the images that gets created are faulty in some way.
When I try to open one, windows says that it cant show me the image because it doesn't support the format? even though its a .png?
what am I doing wrong here?
You should be encoding your data with encodeURIComponent() before including it in POST data.
You should also be using a framework like jQuery to account for browser differences. I guarantee that code will not work the same in all browsers.
On the PHP, try looking into file_put_contents() for writing data. Much quicker to type!
Have you checked what is actually being sent over HTTP? $imageEncoded probably starts with data:image/png;base64,xxxxx
Strip everything up to the comma after base64:
https://stackoverflow.com/a/15153931/3766670
Related
I wan't to know "How to show only image on the url not other content even html?". Like see this url link of Image. This url only shows image not any other content on webpage and also see the url of website it's dynamic url not a specific image url.
So, how to achieve that?
You simply make the request to the URL of the image.
For example, if your image is called test1.png and you have it in a directory called images, you would make the URL like this:
https://your.domain/images/test1.png
If you want to hide the full path to the images and serve them through a page (so you have some control over the request for some reason), you can do something more like the following. Let's call the PHP page img.php. And the request could be like
https://your.domain/img.php/test1
<?php
$request = './default.png';
if (isset($_SERVER['PATH_INFO'])){
$request = './images'.$_SERVER['PATH_INFO'].'.png';
if (! file_exists($request)){
$request = './default.png';
}
}
// we now know we have a valid request and the file was found
header('Content-type: image/png');
header('Content-Length: '.filesize($request));
echo file_get_contents($request);
exit;
?>
With this approach you could have any number of images in the /images/ directory and serve them if they match the request.
The website in your sample maybe using the same $_SERVER['PATH_INFO'] info approach but would be dynamically creating the image using the passed variables and explode('/',$_SERVER['PATH_INFO']) along with imagecreate()
A very quick hack version would be something like the following. The request would be like this:
https://your.domain/test.php/100x50/919/222
And the very quick code, with almost no error checking could be:
<?php
function hexToColor($hx){
$rgb = array(0,0,0);
if (strlen($hx) == 3){
$rgb[0] = hexdec($hx[0].$hx[0]);
$rgb[1] = hexdec($hx[1].$hx[1]);
$rgb[2] = hexdec($hx[2].$hx[2]);
} else {
$rgb[0] = hexdec($hx[0].$hx[1]);
$rgb[1] = hexdec($hx[2].$hx[3]);
$rgb[2] = hexdec($hx[4].$hx[5]);
}
return $rgb;
}
// default values
$sizeW = 100;
$sizeH = 100;
$bg = array(0,0,0);
$fg = array(255,255,255);
if (isset($_SERVER['PATH_INFO'])){
$opts = explode('/',substr($_SERVER['PATH_INFO'],1));
$bgSet = false;
foreach($opts as $k => $v){
// check for a width x height request
if (strpos($v,'x')){
$tmp = explode('x',$v);
$sizeW = $tmp[0];
$sizeH = $tmp[1];
} elseif ($bgSet){
// must be a foreground request
$fg = hexToColor($v);
} else {
$bg = hexToColor($v);
$bgSet = true;
}
}
}
header("Content-Type: image/png");
$im = #imagecreate($sizeW,$sizeH)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im,$bg[0],$bg[1],$bg[2]);
$text_color = imagecolorallocate($im,$fg[0],$fg[1],$fg[2]);
imagestring($im,1,5,5,$sizeW.' x '.$sizeH,$text_color);
imagepng($im);
imagedestroy($im);
exit;
?>
But I would strongly recommend a heap of error checking before using that code!
As I understand you want to dynamically update the picture.
You can see that on their main website they created a form for the entered values:
After that, on the picture URL there are all the values you need to display this image:
https://dummyimage.com/600x400/8a1a8a/232dba&text=xzcxzcnbngh
which is this image:
what you can't see is their server side, which takes the parameters 600x400/8a1a8a/232dba&text=xzcxzcnbngh, creates a picture using their server and returning it to you.
I'll suggest you to create a server side that will return a picture and text based on the given parameters.
based on your server you will need to find out how to create the picture and return it.
As you can see here, I just modified the "src" value of the and it changed the text on the photo.
which means that their server receives the request and send back the image.
If you want a simple solution you could just send back those parameters to your page scripts, and create this image element using JavaScript.
That way, your html code will be clean without even the img element tag.
create your img in JS and send put it on the html body.
Image placeholder that’s updated by scripting
HTML code:
<img id="abc" src="">
Javascript code:
var abcImage = document.getElementById('abc');
abcImage.src = 'https://dummyimage.com/600x400/000/fff';
I'm a php noob forced to add minor functionality to an existing php server. My task is for my php server to return a list of images to the client which will then be displayed on a page.
My JavaScript client code is here:
const http = new XMLHttpRequest();
const url = "http://myaddress.com/myphpserver?";
http.open("GET", url);
http.send();
http.onreadystatechange = (e) => {
console.log(http.responseText);
}
I've tried this code on my server:
$im = imagecreatefrompng("myImage.png");
header('Content-Type: image/png');
imagepng($im);
found here but to no avail
my http.responseText is always empty. Am i going about this the wrong way?
There is no need to send the image as the response from PHP.
What you should do instead instead is return JSON with a URL to the image. Like this:
{
"images": [{
"url": "http://myaddress.com/image_of_cat.jpg"
},
{
"url": "http://myaddress.com/image_of_cat.jpg"
}
]
}
And then with javascript you just set the src attribute of the <img> tag with that URL.
Now you only need to set up a very simple server that serves images from a folder
Does not answer OP's question. Answering for those googlers who actually WANT PHP to send the raw image instead of an image link:
<?php
/* Must be done before headers are sent */
header('Content-Type: image/jpeg');
$path = 'myfolder/myimage.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>
(Partially makes use of another stackoverflow answer on a different question on how to encode image, but if you have the string already encoded from somewhere else, that works as well can replaced the $base64 string )
I don't know if I missed something but I can't receive an image (binary) in javascript. I can do the same in iPhone and Android(with another cose, of course), but not if I'm using javascript.
SCENARIO:
Server Side
I have a server where the image is stored.
Code: (test1.php)
$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';
$bin = file_get_contents($image_url);
echo $bin;
Client Side (Javascript)
I ask to the server, via URL GET/POST, the image, but I can't receive it in Javascript using AJAX request. I want to store it in a .
Code:
var activeXhr = new XMLHttpRequest();
activeXhr.open('GET', 'test1.php', true);
activeXhr.onreadystatechange = function()
{
if(activeXhr.readyState == 4){
var bin_img = activeXhr.responseText;
var dataURL="data:image/jpeg;base64,"+bin_img;
$('#test_img').attr('src',dataURL);
}
};
activeXhr.send(null);
PROBLEMS:
I can't convert this data received in BASE64 or using btoa (returns empty)
QUESTION:
How I can receive an raw image in JAVASCRIPT?
As you do already use jQuery, why not using its Ajax features for requests?
This is also much shorter:
$.get('test1.php').done(function (r) {
// r is your raw image data;
});
Also would it be appropriate to set 'Content-Type' header in php:
<?php
$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';
$bin = file_get_contents($image_url);
header('Content-Type: image/jpeg');
die($bin); // use die/exit for safer output
Did you consider serving Base64 data from php like this:
die(base64_encode( $bin ));
I have a page that has a JavaScript function that uses Post to send a variable to a php file. The problem is, that I am using "header" to download the file and my JS does not open the PHP script in a new page.
When I open the php file in a new page, it does not receive the needed variable from the JS.
I know it sounds confusing, but I hope my code can shed some light on my problem.
The short version is, I am trying to download a file that is selected by a radiobutton. I use JS to check which radiobutton is checked and then send that to my php file. Which then needs to download the file.
Thank you all in advance.
PHP:
<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);
$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);
header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($file);
}
?>
JS:
function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
var str1='radio';
var str2=JSON.stringify(i);
var result = str1.concat(str2);
if (document.getElementById(result).checked){
SelectedRadio = result.slice(5);
}
i=i+1;
}
$.post('accountPage.php',{routenumber:SelectedRadio});
}
When you open the url: http://localhost/accountPage.php in your browser it makes a GET request. You should change all the $_POST to $_GET in your code if you want to make it possible, and then you can open it like this: http://localhost/accountPage.php?routenumber=3, though it's probably not what you really want.
I have a script that generates about 250 images from canvas.toDataURL().
My question is how to save them all at once (one request to server) instead of posting them individually.
I need a way to pack them in single request and then send them to PHP server for unpacking.
canvas.toDataURL() gives the byte data encoded in base64, they are safe to be used as strings and passed through HTTP.
do something like:
var images = [];
while(....) {
images.push(canvas.toDataURL());
}
var imagesJson = JSON.stringify(images);
// pseudo code of jQuery ajax, you can make use of form and a hidden field
// or any other way you'd like to query the server
$.ajax({
....
send:{images:imagesJson}
....
});
with PHP (other server side languages should almost be the same):
$images = json_decode($_POST['images'], true);
foreach($images as $image) {
$image = base64_decode($image);
file_put_contents('<path to file>', $image);
}