Quickest way to output image from an ajax call - php

My project is an image processing script, using php, JavaScript and imagick (or imagemagick).
Currently, a user can change properties of an image with a browser which then jscript sends an Ajax call to my php script to process the changes, resave the image and send the file path and response back to the browser so jscript can then refresh the img tag.
I'm looking to make this process faster if possible.
Ideally, the processing php script would be able to output the raw image data straight after its processed changes with the appropriate mime header, but this can't be done as the same file needs to send a json response.
Any views and suggestions welcome..
EDIT: I should have mentioned what I have tried so far:
Because of the wide variety of operations available to alter the image, telling my php script what to alter via url string like <img src='image.php?id=132&layer1=flip' /> the url would often exceed the recommended maximum number of characters. Otherwise this would have been ideal.
I have also tried sending the base64 raw data back and processing it and although I haven't completely ruled this one out, it's got its drawbacks - adding base 64 data to the src of an <img> is not naturally supported in all browsers.

I don't know if this is the best way, but think about that:
you have to visualize your image with an <img src="">. Now you make following:
User clicks on button -> AJAX Request to Server -> Ajax Response with
URL to browser -> changing the src="" of the image and visualize
it.
replace it with following:
User clicks on button -> changing the src="" of the php file which
processing the manipulation and display it when ready.
give you some explaining code:
<img src="image.php?picid=123123" id="#image"><button id="#rotate90">rotate</button>
<script>
$("#rotate90").click(function(){
$("#image").attr("src","image.php?picid='123123'&do=rotate&what=90");
}
</script>
so you transmit to your php file via picid which pic you mean, do says what function you want to call and what is in dies example the degrees you want to rotate. Your PHP File has to give a Picture back with the correct headers (e.g, header('Content-Type: image/jpeg'); ) and the browser will load the image till the function finishes.

You can include the raw image data as part of your JSON response, and then interpret that raw data accordingly.

I am quite sure, this will not lead to a speedup: You would need to encode the image data, attach it to the JSON, decode on the client, then draw. Additionally chances are, the encoding the image data to a JSON would result in a much bigger volume of data to go ver the wire, negating any speedups, even if there were any.
There is a funny little trickt though, that can shave a bit more than a roundtrip off your latency:
Start your AJAX call to generate the image
Immediately (without waiting for the result) start your image refresh to a PHP script
In this PHP script, wait for the image generation to finish, and then immediately send it (Sort of long poll for an image)
This way you save the time from the moment the image is calculated, up to the new image request arriving on the server:
the result JSON being assembled
return phase of HTTP processing
Network latency downstream
Processing time on client
Network latency upstream for new image request
HTTP processing time for new image request

Related

#only server-side# How to get the echo-html-div-result of the php code saved to png-file on this server?

Like a Log-file is written by a php-script via fwrite($fp, ---HTML---),
I need to save an HTML DIV as png-file on the server.
The client-browser only start the php-script,
but without any client-interaction the png-file should be saved on the server.
Is there a way to do this?
All posts (over thousands) I have been reading are about html2canvas,
which is (as I understand) client-side operating.
I know the html-(html-div)-rendering normally does the browser.[=client-side]
But is there a way to do it in PHP on server-side ?
Reason:
Until now the procedure is
print the div via browser on paper twice
one for the costumer,
one to scan it in again to save it on the server as picture and throw it in the paperbasket.
By more than 500 times a day ...
By security reasons it need to be a saved picture on the server.

Loading/displaying an image with javascript and getting % downloaded

So some background: what I'm doing, is creating a gallery that shows thumbnails of all the pictures in a server directory dynamically (it caches the thumbnails, don't worry). When a user clicks on a thumbnail, a loading gif is displayed until the image is ready, and then the image displayed. The actual pictures are very large in size and might take a considerable amount of time to download to a users computer.
What I would like to do, is show a percentage of the picture that is downloaded while the loading gif is playing.
I realize there are other questions like this, and from what research I've done so far, I also realize this might not be able to be accomplished without some server-side tricks.
From what I have come across in the last little bit, I've gathered (and I could be wrong, so please correct me if I am) is that the client-side code, knows how many bytes are received, but not how large the file is.
So is there a possible configuration using some php/javascript tricks, so that the client side javascript can load an image from a web-server directory and be able to calculate downloaded percentage?
Possibly the php code sending an extra header to the client with file size or something? Or even opening a second request to the web server for file size? How could you get the currently downloaded bytes?
You can use XMLHttpRequest2 to load the data and hook onto the progress events. The loaded data is turned into base64 and added to a Data URI. Once loading has finished you can assign a new image source to the constructed URI.
More info can be found here: http://blogs.adobe.com/webplatform/2012/01/13/html5-image-progress-events/

Uploading image (as data:image/png:base64) to webserver

I have an image on a web page constructed like so:
<img src="data:image/png;base64;...." />
The contents of the image come from the user pasting into the browser. My question is how do I then upload the image to the webserver (PHP if that matters).
1) Take the src attribute with javascript (or the data submitted by user)
2) Submit it to the server 'as is' or cut and submit everything after base64; (AJAX or POST, method GET is probably not very suitable here for large images)
3) Decode base64 on server side (everything after base64; if not cutted), save the result as binary - it is an image.
That's it.
ps: just a reminder - by careful with possible code injection. Check the submitted data or somebody will upload encoded php script. Disable php engine in the folder with uploads and verify that the final result is an actual image (with the help of GD library, for example). Even if the script can not run on your server it could be used for malicious requests to other servers with php scripts.
Just post the base 64 encoded text to your server.
You could save it as...
file_put_contents($image, base64_decode($str));

Need to execute a code in background

I have done a code to receive images from iphone to PHP Server and I need to resize these image and move to 4 folders.
Only then the json respose is giving to iphone. But it takes much time.
Requirement:
i want to move a file to the folder "folder1" then want to give the json response.
the resizing process should do from this "folder1" after giving json response.
How to run this resizing process in background.
Here is my code:
http://pastebin.com/qAcT1yi9
You could always send your php script to run in the background with a Linux command.
Example:
// using backticks to execute the Linux command but there are
// other alternatives
$cmd = `php runScriptInBackground.php &`;
echo $cmd;
First send/upload the images and send a response back, without doing the resize operation.
Then, if the upload was successful, let the browser issue another request and do the resizing. When this succeeds, send the message ‘resizing successful’ back.
A common solution to this problem is implementing a loading/processing message on hitting a specific event. Then - still being displayed - the action will continue to load on the background and the result page will finally be displayed when done.
Although the user must wait, I prefer this above display a result message when the actual result is not known. Unfortunately I'm not sure how this is done on iphone development.
if your building in objective c then you may just resize make a copy and resize it there and send the resized image to your php you could then display a spinner and json result back to the user and also if the is an error the user will still have the resized image to try again with... Also another thought I had was was to use push notification. I don't know what that code would look like but it's something to consider
you need some async javascript or an iframe in your page posting the image to your server and providing feedback to the user.
This means that the 'main' page would not change, but some visual information can be provided to the user.
You can display an animated gif loader or use JS setInterval to give the user the feeling that things are moving forward why waiting for the server to respond.
If the processing is split in more 1 parts, after each step the server could respond with an HTML page and a redirect: this would even work in an IFRAME without JS.
Each 'page' would perform one more step. But if the user closes the browser before all is done you would end with an unfinished task.
A DB, real background processing, and client side JS polling are a more robust alternative.
A full answer would be quite long and require way more details on your settings (apache CGI PHP? or mod_php? are you using an MVC model or framework, or are you writing a page-oriented website?).
If i had to write a full answer I would forget PHP and use Python and celery http://celeryproject.org/ ;-)
PS.
I just found out that a few related questions already existed:
PHP Background Processes
Asynchronous shell exec in PHP
You can do it realy in two times, first send de files and save on first server, after when the user request that you generate the necesary parts.
You will pass the costs from the file sender to the first request from that.

Prevent downloading of a http content body

Currently I've got a web app that retrieves the URL of a mp3 on an external server, but to conserve data I'd like to check first that the page my server is retrieving is actually a redirect, not the actual content (so I can grab the URL of the mp3 and NOT the actual mp3 itself.
The external PHP script requires that json data is POSTed to it, making it hard to get the client to do it themselves.
The problem is that although the external PHP script usually redirects me to a standard URL to GET from, sometimes it returns the actual mp3 itself in the body, using up my bandwidth rather than the user's.
What would be the best solution to fix this to make me not waste my bandwidth?
Thanks.
The best solution would be to use the Http verb HEAD.
From RFC2616
The HEAD method is identical to GET
except that the server MUST NOT return
a message-body in the response.
However, the question is, does the remote server support HEAD?

Categories