Load image... when time is eating up - javascript

here is a sameple code, I would like to know when the browser is REALLY loading image
when you assign an image path to a array like that
imageNames[0] = 'image1.jpg';
or when you make
myImage = new Image();
myImage.src = imageNames[0];
i have put some timer.. but did not get concluant result ! HELP

You would look at the load event. Attach it with the ancient onload or addEventListener()/attachEvent() depending on your browser support requirements.
myImage = new Image;
myImage.onload = function() {
alert('Image loaded');
}
myImage.src = imageNames[0];
jsFiddle.
You could also check if the image is already loaded by checking the complete property.

The key thing to note is that just because a human being can see that something could be a resource identifier / locator, the computer cannot.
When you assign a string to a point in an array:
imageNames[0] = 'image1.jpg';
the fact that 'image1.jpg' is a licit path to an image on your.host.net is not something the browser can determine on its own - the browser cannot recognize that the string 'image1.jpg' is a resource representation rather than a resource itself.
Once you set a DOM image's src property to be the string 'image1.jpg' the browser can recognize the string should be treated as a resource identifier (because the DOM element you created is an image, and the image's src property is supposed to be a URI pointing at an image resource which can be accessed and downloaded) and the browser will try and acquire that resource through means of its own.

The browser downloads the image when you assign a URL to the src attribute of an img element. Try this in the console of your browser and watch the Network tab:
var img = document.createElement('img');
img.src = 'foo';
You'll see network activity as soon as that second line executes.
It most certainly does nothing for imageNames[0] = 'image1.jpg'; since a string in an array could be anything, there's no way the browser has any idea this is supposed to be the URL of an image.

Related

Retrieving image data URi from HTTP response

The Problem: Imagine I have a td element structured as such:
<td td="" colspan="2">
<br>
<img src="ImageServlet" alt="random image" border="0" id="simpleRandomImg">
</td>
of course, with other HTML around it. The image contained within the servlet doesn't have a useful src indicated in the HTML (clearly) - however, when I open up the Network tab in Chrome, I can preview the loaded image itself and copy the image as a data URI - which gives me a stable URL like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAAAyCAIAAACWMwO2AAAhQklEQVR42u2dB1Sb5/nonTRt2pPkJGmSNm180zhNTkabuPGKMeAwxBaIJYEYWmhLSEIggRhaaAIaIEASEggQew+zzPLEdjyy07T/9t9129t129u9z7mP9LnfXxZCBuLeS/71c77zIRQCGj89z+993+d7vS/GH7GxsXH+wGAwCf5ITExMSkpKTk5OSUlJTU1N80d6etcetcetc...
so, clearly there exists a stable reference to the loaded image. And clearly my browser 'knows' what that reference is, because I can retrieve the link to it as a data URI - but there's no reference to that data URI in the actual HTTP response. This probably seems a lot less mystical to someone who understands JavaScript, but that someone is not myself - so could someone explain what's going on here, and if there is some way to gather the data image URI from the HTTP response?
Attemped Solutions:
Did a little digging around in the HTTP response and located this bit of JavaScript which, apparently, handles the changing of images:
function changeImage() {
// makes a new image load
var obj=document.getElementById('simpleRandomImg');
if (obj != null) {
// append a unique index to force browser to reload
obj.src='ImageServlet?'+(cnt++);
}
However, nothing I see there gives any indication as to the actual URI location of the image. As before, if I open the Google Chrome network tab and attempt to retrieve the data image URI from the individual response, it works and gives me a valid URI - so, clearly the browser is receiving it. How can I access it?
e: to be clear, I do not control the website in question, so I can't 'fix' it by just changing the internal javascript - I'm viewing the site and am interested in whether or not it's possible to retrieve the loaded images short of screenshotting the page itself.
Something like this should work. Canvas API has a function called toDataURI
function getDataUri(url, callback) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/jpg').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/jpg'));
};
image.src = url;
}
// Usage
// beware of server cors settings..
getDataUri('image url here', function(dataUri) {
console.log(dataUri)
// Do whatever you'd like with the Data URI!
});
You can set the src of the image to your URI by using setAttribute, like so:
obj.setAttribute('src', uriString)

Receive text and picture from server in javascript

I need to refresh an img tag every second. so I wrote a little bit of code that changes src attribute of img tag and it loads the picture from image.php.
All good.
Sometimes the image.php doesn't have a picture, or sth went wrong in image.php. I need image.php to send a message along with the picture to determine validity of the picture, or tell me the error number.
so I need a php code that puts a text and a picture in it's output.
Right now I use
//code
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
and image.php acts like a .jpg file and I can use it in src attribute of img tag. But I need a way to find out if image.php is outputing a valid image and not a php error.
js code:
var newImage = new Image();
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("myimg").src = newImage.src;
newImage = new Image();
newImage.src = "socket.php?message=0&image" + count++ + ".jpg";
}
}
JavaScript-wise, you can find out about image failing to load via error event (jsfiddle).
Perhaps, you could request the same URL via Ajax if the image fails to load, to obtain the error message. Unless you'd want to encode error messages as images too (and decode them client-side), of course, which may, or may not be a good idea.
First method:
Using onerror property of the img element:
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Source
You can use function as value of onerror property and use this function in java script. Example is below.
HTML:
<img src="image.gif" onerror="handleError();">
JS:
function handleError() {
// do something
}
Another way is to set onerror handler to instance of Image class:
var image = new Image();
img.src = /* url to the imgage */;
image.onload = function() {
// assign img.src to to src property of the `img` element
}
image.onerror = function() {
// do actions on error
}
Note:
2nd way is the way how to use new Image() correctly.
I would use Ajax for such a task, and send back the image path and any other added information from the server.
The Ajax response can be easily read by the client.

Element Background Image DataURL

Is there any way to get a callback on background-image is loaded with a base 64 DataURL. I can cache this with image src attribute, but with data url ? How ?
Should work the way it usually does:
var image = new Image();
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUh.......";
image.onload = function() {
//image was loaded
};
Caching by the browser is of course disabled for Base64 strings, that's why it's normally only used for small images, like icons and stuff.
You can convert images to Base64 online here : http://base64img.com/#encode
Note that some browsers can have limitations on size for Base64.
Seems that style.BackgroundImage property do not set the value asynchronously. So my problem is solved.

Determine through javascript if another URL exists

I am working with a servlet which serves up an image. However, it takes about 30 seconds for this to be generated. When complete, it appears on an OpenLayers interactive map.
I am trying to figure out a way for the user, who is at www.test.com to get confirmation the image is being processed or is complete, which is located at www.test2.com. If I open test2.com, I can see that the page is trying to load. When complete, the image also appears on my map on test.com.
However, I can't figure out how to test if this image exists or not. I am looking for something probably like
if(image exists at http://test2.com) {alert("request is done");
or possibly
if(http://test2.com is loading) {doing something);
I just don't want the user sitting by if the request fails. If it fails, the url will complete its load - however, no image will appear. Any guidance will be very appreciated! Thanks!
Kyle
If it is a different server, JavaScript will not be able to make any type of Ajax request to that server to see if it exists. You would have to have a proxy on the local domain which could make a head request to the second domain.
If you are waiting until the image is loaded to work with it, you can always do an image preloader, but that will take the full time for the image to render before the onload event fires.
var img = new Image();
img.src = theUrl;
img.onload = function() {
nextStep(this);
};
img.onerror = function() {
imgLoadingError(this);
};
IF you have control over the other server, you could put a small image on that server and do something like this: (Untested code, typed in directly)
var img = new Image();
// Note the order of these two statements
img.onload = function()("The image loaded! Server must be up");
img.src = "http://example2.com/myflag.png";

Create HTML image from data in Javascript variable

I have image data (either JPEG or PNG) in a Javascript variable. How do I display the image in an HTML document? These are very large images and code like this doesn't work because the URI is too long:
// doesn't work because the URI is too long
$('img#target').attr('src', 'data:...');
Using canvas is probably the answer but I cannot figure out how to load it with the image data.
In case you are wondering: no, I cannot just download the image data directly to the img tag. It came from the server encrypted and was decrypted within the browser using Javascript.
Thanks,
-- Art Z.
To use a data URL to draw on a canvas:
var img = new Image;
img.onload = function(){
myCanvasContext.drawImage(img,0,0);
};
img.src = "data:...";
Per this question/answer be sure that you set the onload before the src.
You say that "the URI is too long", but it is not clear what you mean by this. Only IE8 has a 32kB limit on the data URI; for other browsers it should work fine. If you are experiencing an error, please describe it.
It turns out that
$('img#target').attr('src', 'data:...');
does work in all except IE. My problem originated elsewhere.

Categories