Checking if an image is missing from folder in javascript - javascript

I am making a small slide show application to show images inside an html.
The name of images are something like:
"MOD01_001.jpg"
"MOD01_002.jpg"
"MOD01_004.jpg" and so for...
Sometimes one or more images is missing and the previous images still is in the cache, so I can't check if the new image was loaded checking for the width/height properties.
What can I do to check if an images are missing from the list (I know I can't access the file info from inside client browser).
TIA

This loads them all in, so it could be really terrible:
var images = ['MOD01_001.jpg','MOD01_002.jpg','MOD01_003.jpg'];
for (i in images) {
checkIfImageExists(images[i]);
}
function checkIfImageExists(image_path) {
var img = new Image();
img.onerror = function(){
console.log('Could not load image: ' + img.src);
}
img.onload = function(){
console.log('Loaded image: ' + img.src);
}
img.src = image_path;
}

Related

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

How can I get the width and height of an image before completely loaded with JavaScript? [duplicate]

This question already has answers here:
Get image dimensions with Javascript before image has fully loaded
(3 answers)
Closed 6 years ago.
I tried to get the actual size of images before they are displayed on HTML, and I do use this in most cases:
var imgae = new Image();
image.src = img.src;
image.onload = function() {
// Do something with image.width and image.height
// and insert an <img> into <body>
}
However when the image is too large so that it may take seconds to download, users have to wait until it completes before seeing the image. Is there any way where I can get the information before Image.onload is triggered (and of cause after the meta data of image is loaded), so that I can show part of it on the page?
If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.
$(document).ready(function() {
$("img").load(function() {
alert($(this).height());
alert($(this).width());
});
});
If you are using jQuery 3.0 remember that load method was removed, use
$('img').on('load', function() {})
var _URL = window.URL || window.webkitURL;
function displayPreview(files) {
var file = files[0]
var img = new Image();
var sizeKB = file.size / 1024;
img.onload = function() {
$('#preview').append(img);
alert("Size: " + sizeKB + "KB\nWidth: " + img.width + "\nHeight: " + img.height);
}
img.src = _URL.createObjectURL(file);
}
You can make your function asynchronous with simply using an appropriate callback:
function loadImages(imgsrc, callback) {
var image = new Image();
image.onload = callback;
image.src = imgsrc;
}
and then you can call this function easily like this
loadImages('you image src', function() {
// whatever code to be executed
});
Hope if works for you.

Getting an image width and height from Phonegap before upload

This should be easy but I can't find the answer. I need to get the width and height of an image, grabbed via a fileURI in Phonegap, before uploading it to our server. Certainly there's got to be some html5 / Phonegap magic that will do this before uploading. Here is some really reduced code to show where I'm at:
function got_image(image_uri) {
// Great, we've got the URI
window.resolveLocalFileSystemURI(image_uri, function(fileEntry) {
// Great, now we have a fileEntry object.
// How do we get the image width and height?
})
}
// Get the image URI using Phonegap
navigator.camera.getPicture(got_image, fail_function, some_settings)
Any idea what the missing piece is? I wish I had Simon MacDonald or Shazron on speed dial, but I do not.
Here is a proper solution.
Pass this function an imageURI. URIs are returned from both of PhoneGap's getPicture() methods.
Like this:
get_image_size_from_URI(imageURI)
function get_image_size_from_URI(imageURI) {
// This function is called once an imageURI is rerturned from PhoneGap's camera or gallery function
window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
fileEntry.file(function(fileObject){
// Create a reader to read the file
var reader = new FileReader()
// Create a function to process the file once it's read
reader.onloadend = function(evt) {
// Create an image element that we will load the data into
var image = new Image()
image.onload = function(evt) {
// The image has been loaded and the data is ready
var image_width = this.width
var image_height = this.height
console.log("IMAGE HEIGHT: " + image_height)
console.log("IMAGE WIDTH: " + image_width)
// We don't need the image element anymore. Get rid of it.
image = null
}
// Load the read data into the image source. It's base64 data
image.src = evt.target.result
}
// Read from disk the data as base64
reader.readAsDataURL(fileObject)
}, function(){
console.log("There was an error reading or processing this file.")
})
})
}
The following code solves the same problem for me today (tested on iOS):
function got_image(image_uri)
{
$('<img src="'+image_uri+'"/>').on('load',function(){
alert(this.naturalWidth +" "+ this.naturalHeight);
});
}
Hope it helps!
I think you can use target width and height of getPicture() to limit the maximum dimension.
If you need to send them to server, I think server code would help to get those dimension.
If you really need to get those dimension by js, you can
var img = new Image;
img.onload = function(){
myCanvasContext.drawImage(img,0,0);
};
img.src = "data:YOUR_BASE64_DATA";
And you can do it with img
1.Phonegap supply a way to specific the size of the image you choose
Click here to see the options
2.If you need to know the original size and do not want to specific, you may try the code below:
function got_image(image_uri) {
window.resolveLocalFileSystemURI(image_uri, function(fileEntry) {
fileEntry.file(function (fileObj) {
var fileName = fileObj.fullPath;
var originalLogo = new Image();
originalLogo.src =fileName;
//get the size by: originalLogo.width,originalLogo.height
});
})
}
one way you can do this is by using the MediaFile from the Capture API.
var mediaFile = new MediaFile("myfile.jpg", "/path/to/myfile.jpg");
mediaFile.getFormatData(function(data) {
console.log("width: " data.width);
console.log("height: " data.height);
});
Should be a lot less code than the current accepted solution.

JavaScript/jQuery: Running DOM commands *after* img.onload commands

I need to get the width & height of a CSS background image and inject it into document.ready javascript. Something like:
$(document).ready(function(){
img = new Image();
img.src = "images/tester.jpg";
$('body').css('background', 'url(' + img.src + ')');
$('body').css('background-size', img.width + 'px' + img.height + 'px');
});
The problem is, the image width and height aren't loaded in at the time of document.ready, so the values are blank. (They're accessible from console, but not before).
img.onload = function() { ... } retrieves the width and height, but DOM $(element) calls aren't accessible from within img.onload.
In short, I'm a little rusty on my javascript, and can't figure out how to sync image params into the DOM. Any help appreciated
EDIT: jQuery version is 1.4.4, cannot be updated.
You could use $.holdReady() to prevent jQuery's ready method from firing until all of your images have loaded. At that point, their width's and height's would be immediately available.
Star by calling $.holdReady(true). Within the onload method of each image, check to see how many images have been loaded all together, and if that matches the number of expected images, you can $.holdReady(false) to fire the ready event.
If you don't have access to $.holdReady(), you could simply wait to spit out your HTML until all of the images have loaded by still calling a function:
var images = { 'loaded': 0,
'images': [
"http://placekitten.com/500/500",
"http://placekitten.com/450/450",
"http://placekitten.com/400/400",
"http://placekitten.com/350/340",
"http://placekitten.com/300/300",
"http://placekitten.com/250/250",
"http://placekitten.com/200/200",
"http://placekitten.com/150/150",
"http://placekitten.com/100/100"
]};
function outputMarkup() {
if ( ++images.loaded === images.images.length ) {
/* Draw HTML with Image Widths */
}
}
for ( var i = 0; i < images.images.length; i++ ) {
var img = new Image();
img.onload = function(){
outputMarkup();
};
img.src = images.images[i];
}

Image preloading with array

I am using the following code to preload images in an image gallery:
$(window).bind('load', function(){
var imageNumber = $(".image").attr("alt");
var imageUp = parseInt(imageNumber) + 1
var imageUp2 = parseInt(imageNumber) + 2
var imageDown = parseInt(imageNumber) - 1
var preload = [
'image' + imageUp + '.jpg',
'image' + imageUp2 + '.jpg',
'image' + imageDown + '.jpg',
];
$(document.createElement('img')).bind('load', function(){
if(preload[0]) this.src = preload.shift();
}).trigger('load');
});
I modified another basic javascript/jQuery preload script, adding variables in order to get a numeric value from the current image's alt-tag and preload images that are immediately before and after it (n+1 n+2 n-1) in the gallery. This works, though I imagine it may be kind of ugly.
What I want to do is add or call another array containing all images in the directory, so that after the previous and next images have loaded, the current page continues to preload other images, saving them in the browsers catche for future viewing as the user moves through the gallery.
Ideally, this second array would be called from an external .js file, so as to prevent having to update every page individually. (Or maybe it would be easier to save the entire script in a external .js file for each directory and fill out the rest of the array based on that directory's contents?).
Web design is only a hobby for me (I'm a photographer), so my knowledge of javascript is limited--just enough to customize pre-built functions and collage scraps of code.
I would really appreciate if someone could point me in the right direction on how to modify my code.
Thanks in advance,
Thom
I have never used a jQuery preload script but i have done a lot of preloading with 'vanilla' javascript.
Try the code i have added below, it may solve your problem.
function preLoad() { // my preload function;
var imgs = arguments, imageFolder = [];
for (var i = 0; i < imgs.length; i += 1) {
imageFolder[i] = new Image();
imageFolder[i].src = imgs[i];
}
}
var gallary = []; // all gallary images
$(window).bind('load', function(){
var imageNumber = $(".image").attr("alt");
var imageUp = parseInt(imageNumber) + 1
var imageUp2 = parseInt(imageNumber) + 2
var imageDown = parseInt(imageNumber) - 1
var preload = [
'image' + imageUp + '.jpg',
'image' + imageUp2 + '.jpg',
'image' + imageDown + '.jpg',
];
$(document.createElement('img')).bind('load', function(){
if(preload[0]) this.src = preload.shift();
}).trigger('load');
preLoad(gallary); // preload the whole gallary
});
EDIT
preLoad() : this function accepts image urls as arguments e.g preLoad('image_one.jpg', 'image_two.jpg','image_thre.jpg');
The preLoad function has two variables var imgs and var imageFolder, imgs stores all the image urls and imageFolder stores image Objects, that is, preload loaded images.

Categories

Resources