Detect whether Image is broken in Javascript - javascript

I'm adding images to an HTML5 canvas using Javascript:
img = new Image();
img.addEventListener('load', loadCallBack, false);
img.src = image_url;
And then loadCallBack draws the image.
The problem is that sometimes the image_url refers to a broken or nonexistent image. When this happens, I get a 404 error in the console and the image on the canvas stays white. Instead, I'd like to be able to replace the image's src attribute with another image_url.
I tried the following and it did not work:
img.addEventListener("error", function(){console.log("404");});
How can I detect the 404s of the images?
Note: I'm still looking for a solution, as neither of the two posted so far has worked.

The same code as the Kostia's answer: just to compare the ugliness of jQuery and the beauty of vanilla javascript:
function brokenImage() { ... }
img = new Image();
img.onerror = brokenImage;
img.src = "invalid_img_name.png";​

Works in jQuery for me... http://jsfiddle.net/5v2qG/
img = new Image();
$(img).bind('error', function () {
alert('error called');
});
img.src = "invalid_img_name.png";​

Related

Getting the actual image from an input with type=image

I have an input element with type=image:
<input type="image" src="some/url/that/generates/new/image">
I want to load that image into a canvas element. Usually I would do:
var img = new Image();
img.onLoad = function () {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
};
img.src = inputElement.src;
However, in this case I can not use the src attribute because doing so would generate a new image (the src points to a url that generates a new random image).
Any other ideas how to get to that image once its already loaded? In the chrome devtools I can see the image under the "Sources" tab, so its there...
--- edit
I should have mentioned that the html is not under my control, I am writing a chrome extension and I want to save to that image of the input tag (by attaching it to a post request, that already works. I just dont want to generate a new image by using the src attribute)

javascript image onload has 0 width and 0 height

I am loading an image from the file system and then I want to resize the image. it works fine in all browsers except for IE (11). Problem is that the image is loaded, but the width and height are 0.
I am out of options so I am posting this question here.
This is the code
function getAsImage(readFile, chatboxtitle) {
var reader = new FileReader();
reader.readAsDataURL(readFile);
reader.onload = addImg;
}
function addImg(imgsrc) {
var img = document.createElement('img');
img.setAttribute("src", imgsrc.target.result);
console.log(img);
console.log(img.width + " "+img.height);
... a lot of cool stuff happens here but it doesn't work because width is 0
}
OK, so the console prints the image which is like
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAH0CAYAAAHUIW ... and much more.. >
So the image IS there. All browsers work fine except IE.
I tried to play with setting some IMG properties like style, width but none work.
Note, I am not a hardcore JavaScript developer. Maybe I am missing something. Is the DOM element not found?
UPDATE
I tried the answer below yesterday and it was working. But I tried the solution today and it is not working anymore. Try this fiddle .
It is not working in IE11 on Windows7 but it is on IE11 on Windows8.
Weird IE behaviour. It turns out that you need to set src using
img.src = src_goes_here
Not via setAttribute
(function(doc){
doc.getElementById('file').addEventListener('change', readFile);
function readFile(ev) {
var file = this.files[0],
reader;
if(file) {
reader = new FileReader();
reader.onload = getSize
reader.readAsDataURL(file);
}
}
function getSize(ev) {
var img = doc.createElement('IMG');
img.src = this.result; //wors in IE11
//img.setAttribute('src', this.result); //doesn't work
console.log(img.width, img.height);
}
}(document))
Demo.
UPD: Some additional research shows that in order to make IE to calculate image sizes when you set src using img.setAttribute you need to actually attach the image to the document. For example
document.body.appendChild(img);
Another Demo.

Saving and loading an image from localStorage

So basically, I am trying to save an image into localStorage, and then load that same image on the next page.
I came across this great example: http://jsfiddle.net/8V9w6/
Although, I have absolutely no idea how this works since I have only ever used localStorage for extremely small strings.
I have an image that gets changed via a file upload handled by jQuery
<img id="bannerImg" src="images/image-placeholder.jpg" alt="Banner Image" style="display:none;" width="100%" height="200px" />
The jsfiddle link I added above allows multiple file upload, and that is definitely something I would not like to have.
What I need to know is what should I be placing on the first page to save the image, and what should I be placing on the second page to load the image?
I have a save button that will be processing everything.
Something like this ?
var img = new Image();
img.src = 'mypicture.png';
img.load = function() {
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var data = context.getImageData(x, y, img.width, img.height).data;
localStorage.setItem('image', data); // save image data
};
Get the localStorage on the second page; try something like this:
window.onload = function() {
var picture = localStorage.getItem('image');
var image = document.createElement('img');
image.src = picture;
document.body.appendChild(image);
};

Detecting and dealing with 400 errors inside img tags

I am developing an app that embeds users' Facebook profile picture(http://graph.facebook.com/(fb id)/picture) inside an img tag. And it works...for the most part. However I will occasionally get 400 errors when I request the profile picture(see this)
Is there any way I can detect these 400 errors with Javascript/JQuery? Right now they are being displayed as a broken image....
This is pretty simple using the onerror event.
We can simply create a new image in JavaScript and attach two events to it - onload and onerror. Then setting the image src will make the browser download the image, firing the onload event if it is a true image, or onerror if not.
var img = new Image();
// This URL will return an image an fire `onload`
img.src = 'http://placekitten.com/300/300';
// Replace the line above with this one to load a fake/unavailable image, which will fire the `onerror` event.
// img.src = 'http://mybrokenurl';
img.onload = function() {
document.body.appendChild(img);
}
img.onerror = function() {
alert('Error loading image');
}​
Demo: http://jsfiddle.net/amustill/vSJ4F/

How do you use the Pixastic fastblur to blur all the images on a page onLoad?

On http://www.pixastic.com/lib/docs/actions/blurfast/ , their tutorial shows how to blur a single image.
var img = new Image();
img.onload = function() {
Pixastic.process(img, "blurfast", {amount:0.5});
} document.body.appendChild(img);
img.src = "myimage.jpg";
How would I go about blurring all the images on a page and then making a button to revert them back to their original unblurred state?
Thanks in advance!

Categories