Reading Image from AJAX response - php

I have a url that when requested will return an image. I want the url to be requested through an AJAX request. The ajax request returns binary data which is what is being deplayed. but i want the actual image displayed not the binary data. Am using php on the server side and i have set the below headers:
header("Cache-Control: no-cache, must-revalidate");
header ("Content-type: text/jpg; charset=windows-1251");
Please i need advise on what i need to do.

You need to send an url to this Photo, even if its just a PHP file with an ID
For example
<img src='thumbGenerator.php?id=1337' />
And then this PHP file outputs the binary data.

You need to read up on data urls for binary image data. Keep in mind this method isn't supported in Internet Explorer. If you need cross-browser compatibility then you will need to store the files somewhere on the server and link to them using the images src attribute. Or link the src attribute to a php script that generates the images and serves them correctly.

Related

Server generated dynamic image and long URL

I need to display an image that is generated by the server. It is generated based on parameters supplied via URL. Problem is, parameters can be very numerous and long and as we know there is a limit to GET request length.
Here is a simplified version of the code:
View:
<img alt="Preview" src="/preview/getPreview/?id=1&page=1&values=%7B%22object_82%22%3A%22Test%22%2C%22object_83%22%3A%22Test2%22%2C%22object_84%22%3A%22Test3%22%7D&size=676">
This is a very short list of parameters there will be much more. As you can see values is actually a JSON stringified array.
The controller part of the code is more or less like this (not sure if it's actually relevant to the question but still here it is):
function getPreview() {
$buffer = createImageFromData($id, $page, $values, false);
$img = new Imagick();
$img->setResolution(300, 300);
$img->readimageblob($buffer);
header("Content-type: image/jpeg");
header("Content-Length: $lenght");
header("Content-Disposition: inline; filename=preview.jpg");
echo $img;
}
So the question is - how to display server generated dynamic images without having to do the src='' part that will simply get too long for some images.
If you have a lot of information that you need to pass to the server. A get request is going to run out of space on older browsers fast: maximum length of HTTP GET request?
What you could do is using javascript, post the information to your server first before you show the image. If you would like to save the data to a database an return an ID that would be a good solution, you can then load the image with:
<img src="/preview/getPreview/?id=312">
If you do not want to save the data you could return a base64 encoded image directly, this isn't supported in < IE8 very well though. A response could look like:
<img src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="alt="Base64 encoded image" width="150" height="150"/>
I mentioned that you should post via javascript so the generation wouldn't have to reload the page. This however is something you do not have to do.
Also - If you are generating the same image over again. We have experienced large page loading times due to the image creation script - So would suggest to cache the image if you can.
Maybe if you update your question to specifically state what your intentions are and what images you are trying create, I could taylor this answer better.

How to get current URL in a PHP image?

I want to get current URL inside a PNG generated by PHP (header('Content-Type: image/png');)
But when i use http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];,
The URL output is the file's location (http://test.com/png.php) but not the page which get the img with <img> tag.
What can i do to get current URL?
Thanks!
Sounds like you're looking for $_SERVER['HTTP_REFERER'], not REQUEST_URI.
I'm not sure I understood you, but I'll give it a go. If you serve an image via PHP, it's URL will always point to a PHP script. If you want it to look like it's really a .png image, you have 2 choices:
1) Create a rewrite rule which will redirect some .png URL to your PHP script and then serve that URL to users.
2) Stick with the current URL, but also add an (non-standard!) Content-Disposition header:
header('Content-Disposition: attachment; filename="my_image.png"');
This way the URL will still point to a PHP script, but when a user tries to save the image, the suggested name won't be the PHP script, but the name specified in Content-Disposition.

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.

Google Contact API Picture Data, returns data, but I dont know how to display it with PHP

I am using OAuth 1.0, I am getting the contacts just fine. Next I fetch an image using the link that is in the contact info. If the user has an image the request works and return a bunch of data. When I echo it I get something like this:
"" ÿÀ``"ÿÄÿÄ<!"12A#Qq‘BRa3‚’±Ñðbrƒ¡Â$%¢³ÿÄÿÄ#!1Q"AaqÿÚ?ôÌìç™pzõWoÂ~vïD±èÐvQNl/žåÐìMCÀƒÚüü¿ ÔLß÷&‹ðKš×aG¥=Ë È
Which I am assuming is the data for the image. Now that I have this, I cant figure out a way to display it.
here is an example of what I am doing:
$consumer = new OAuth($key,$secret);
$image = $consumer->fetch($theImageUrl);
return $image;
The request is working, theres no 400,401, or 404 errors.
I tried doing this already:
<img src="/art/transperantimage.png" style='background: #fff url(data:image/png;base64,<?=$image ?>) repeat-x bottom'/>
and I just ended up with more data jibberish.
I guess my question is how the heck to I display this data?
Per the documentation, this request returns the bytes of the image. So you have three options:
Write a PHP script that outputs those bytes (and only those bytes) directly to the client using the appropriate Content-Type header, which is what #Prowla has in mind. Then point to this script in your <img src="...">.
Write the bytes to a publicly-accessible file on your web server, and then put the URL of that file in your <img src="...">.
Use a data URI, which you seem to have attempted, but forgot that you need to Base64 encode the data first, e.g.:
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image ); ?>" />
While #3 is looks the simplest, #2 is probably the best solution since the image likely doesn't change very often so there's no sense requesting it from the API every single time someone reloads your page. You can just write the image to a file if the file doesn't already exist, and then periodically (e.g. every day or week) check to see if there is a new image and if there is, overwrite the old one.
Before printing out the image set the header content type to something like (depending on the data type):
header('Content-Type: image/jpeg');

How do I load an image in PHP

I want code that loads an image to a PHP server and then send it to browser.
For example I want sample.php to send an image to browser once it is requested.
in other words, I want to create a PHP file that acts like a proxy for an image.
why are you doing this?
why don't deliver the image directly?
if you are trying to display a random image you may as well just redirect to the image using
header("Location: address-of-image");
for delivering the file to your clients from your server and not from its original location you can just do. however your php.ini settings need to allow external file opens
readfile("http://www.example.com/image.jpg")
correct headers are not required if you are going to display the image in an img tag,
altough i would recommend it. you should check the filetype of the image or in most cases just set an octet-stream header so the browser doesnt assume an incorrect type like text or something and tries to display binary data.
to do so just do
header("Content-type: application/octet-stream")
one more thing to consider may be setting correct headers for caching...
You need to use
$image = fopen("image.png");
Modify the headers(not sure exacly if it's correct)
headers("Content-type: image/png");
And then send the image
echo fread($image, file_size("image.png"));

Categories