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.
Related
I have a very simple code snippet to set a background image of an element once the image has loaded on a new image object.
var img = new Image();
var myelement = document.getElementById('myelement_id');
img.addEventListener('load', function(){
myelement.setAttribute('style', 'background-image: url(/public/images/myimage.jpg)');
});
img.src = '/public/images/myelement.jpg';
This question has already been asked a few times but answers have not been satisfying.
It's not the size of the image. The load event isn't fired no matter the size or format of the image.
The error event is not fired neither. Some people suggested that the error event will be fired instead of the load event on IOS.
It's not the browser. It's IOS. The behaviour is the same on Safari or Chrome on IOS.
It's not observable with BrowserStack. The image loads fine on BrowserStack yet a physical device is incapable of firing the load event.
I do assign the function first and thereafter set src to trigger the load event.
This seems to be working for me. But I am not sure whether changing the add event listener to the .load event made the difference.
function imgLoad(_imgDOM, _imgID){
_imgDOM.setAttribute('style', 'background-image: url(/public/images/load/' + _imgID + '.jpg)');
}
var imgLoadArray = document.querySelectorAll('.img__load');
for (var i = 0; i < imgLoadArray.length; i++) {
var imgDOM = imgLoadArray[i];
var imgID = imgDOM.getAttribute('id');
var img = new Image();
img.onload = imgLoad(imgDOM, imgID);
img.src = '/public/images/load/' + imgID + '.jpg';
}
all.
I have a really strange bug, on which i spent a lot of time and haven't solved yet...
I have this fiddle:
http://plnkr.co/edit/Ctuvyom1VEuff6yD3gls?p=preview
$scope.photoChanged = function(files) {
$scope.files = files;
var reader = new FileReader();
reader.onload = function(e) {
$scope.imagecontent = e.target.result;
if (!$scope.$$phase) {
$scope.$apply();
}
};
reader.readAsDataURL(files[0]);
};
and in chrome, ff, opera, safari - when i upload image to browser until it is displayed i see css animation
but!
in ie 10/11 i see that browser window is busy, and css animation is busy to: no animation. also i try to set gif animation: but still huge base64 image took all resources
maybe anybody could give advice how to be, and in which side to see? really, i'm confused, i didn't know how to solve it(( loader is stoppped (paused) in ie.
also images, which i try to upload to browser:
https://dl.dropboxusercontent.com/u/59666091/Victory-squarepngpngpng.png
https://dl.dropboxusercontent.com/u/59666091/19af71228a66376d950e32cc065ff250.png
I have a function where I get the img src value as the parameter, what I want to do is check to see if that image loads with a 200 ok or 404/some other error. If it gets a 200 ok, then I want to inject an img tag with that src into the DOM(I reason that during checking,it also gets loaded into the browser cache and injecting that img tag into the DOM loads it from the cache ). I tried with a simple snippet of code as follows :
function checkImage(src)
{
var img = new Image(),
tag = '<img src="'+src+'" />',
alt = '<span>sorry,image broken</span>';
img.onload = function(){
$('.some-container').html(tag);
};
img.onerror = function(){
$('.some-container').html(alt);
};
img.src = src;
}
It worked fine in chrome, but went havok in firefox and ie(both of them are firing only the error event no matter whether the image loaded fine or broke). Instead of using onload and onerror, I tried it using jquery like :
$(img).load(...).error(...).attr('src',url);
$(img).on('load',...).on('error',...).attr('src',url);
$('<img />').load(...).error(...).attr('src',url);
$('<img />').on('load',...).on('error',...).attr('src',url);
and even tried the jquery.imagesLoaded plugin by desandro(https://github.com/desandro/imagesloaded) like :
$(img).imagesLoaded().done(...).fail(...);
$(img).imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
$('<img />').imagesLoaded().done(...).fail(...).attr('src',url);
$('<img />').imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
I also tried the solutions from :
jQuery callback on image load (even when the image is cached)
https://groups.google.com/forum/#!topic/jquery-dev/7uarey2lDh8
but as it turns out, works in chrome, but not in FF or IE, is there any solution where I can check for an image which is present in memory but not in the "DOM" ? Thanks in advance.
You have to check for image onload after setting a source to it.
var img = new Image();
//set source to the image
img.src = "set/image/source/path"
img.onload = function(){
//if image load is successful
//create an jQuery object out of this image
var jQimage = $(this);
$('.myContainer').html(jQimage);
}
Also note that jQuery load function cannot guarantee you a cross browser check for image loading as mentioned in jQuery docs
So, the best approach is to check onload with native javascript and create an jQuery object if necessary to make use of jQuery methods.
Have a look at what w3schools has to say about the Image() javascript object.
http://www.w3schools.com/jsref/dom_obj_image.asp
onabort - Loading of an image is interrupted, W3C YES
onerror - An error occurs when loading an image, W3C YES
onload - An image is finished loading, W3C YES
also the complete property of the Image() object, determines if the browser is finished loading an image, Unfortunately this particular property is not W3c
hope that helps a little
PS: After having a little Google search I found this Q/A from Stack overflow.
Cross-browser image onload event handling
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";
I'm modifying some images on canvas and then setting src of this images to new base64 coded pictures.
img.src = changeColor(img);
changeColor returns base64 coded image:
return canvas.toDataURL();
Chrome and Opera are refreshing images after src change, but firefox don't!
I also inspected the image element by FireBug, and it shows new src and new image!
I have already tried to add Data to URL but uhh... this is a base64 coded image, not an url, so it breaks my pictures totally.
I there any way to force reload images or disable firefox cache via javascript?
UPDATE:
I have also tried to set image.src=''; in changeColor function.
It works in chrome, but in firefox... picture disappear, and do not appear again when i set new base64 value.
It's working for me as #dmmd mentioned. You only need to add query string with a random value.
id.src = "path?t=t"+ Math.random(5);
I am not using image data, but this worked for a similar issue where FF was not reloading when the src variable didn't change:
image.src = "";
setTimeout(function(){
image.src = //the new image src
}, 0);
Try adding the image format (and use jpg). It may re-encode the image:
return canvas.toDataURL('image/jpg');