Validate an image path in javascript - javascript

I have an image like: img src="" class='listPartialLoader' alt='loading'
I am assigning the 'src' value with data from an ajax call. Some times if the image is not found I want to add a default image path like"Images/default.jpg". But how can I check whether the image is exist or not using javascript? (Basically I want if the image is not found add a default image)

You should be able to check if the image exists with the onerror and onload events.
var myImg = new Image;
myImg.src = 'path/to/image';
myImg.onerror = function(){
console.log("Error!");
}
myImg.onload = function(){
console.log('Loaded!');
}

While you are retrieving the value for src property during the ajax call to the server, why not check if the file exists?
string src = GetSrc(); //whatever you need to do
if(System.IO.File.Exists(HttpContext.Current.Server.MapPath(src)))
{
return src;
}
else
{
return "path/default.jpg");
}

if the image is in the same domain of your script just take the image path (before assign it to image element) and make a simple HEAD ajax request to that path (eg. "images/default.jpg) . If server status is 304 or 200, the image exists

Related

Ember cli replace image standard if image model is null in json

I want to display a standard image if the model in my json is null.
This is my function where first i successfully achieve to format the url in order to make it bigger (eg: https://i1.sndcdn.com/artworks-000121961221-bzjnxn-large.jpg to https://i1.sndcdn.com/artworks-000121961221-bzjnxn-t500x500.jpg) but then i can not assign a standard image when the model (artwork_url) is null.
formattedArtwork: Ember.computed('artwork_url', function() {
var splitURL, url;
if (this.get('artwork_url')) {
url = this.get('artwork_url');
splitURL = url.split('-large');
return splitURL[0] + '-t500x500' + splitURL[1];
} else {
url = this.get('https://mystandardimage.jpg');
return url;
}
}),
So if it gets the arwork_url i can format and display the img but if it does not get i would like to put a general image url i created, at the moment it says that my url is undefined although that url (https://i1.sndcdn.com/artworks-000121961221-bzjnxn-t500x500.jpg) really exists.
What am i doing wrong?
See the printscreen
After the debugger line, you should just return "https://i1.sndcdn.com/artworks-000121961221-bzjnxn-t500x500.jpg"

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.

Changing image extension with javascript/jquery only?

I'm making a simple slider to show off artwork for a friend of mine. I'm really only familiar with javascript/jquery, so I'm not 100% comfortable using something else right now.
Since my friend doesn't have any programming knowledge, I'm trying to keep this really simple for her to update (i.e., automating creating new images whenever she adds a new one to the folder). She will upload images to a folder and will have to number them (i.e., 1.jpg, 2.jpg). My javascript uses a for loop to loop through numbers (she will have to update the loop whenever she adds a new image) and insert them into the file name. HOWEVER this limits her to only uploading one type of file. Is there someway to change the extension only using javascript?
This is what I have so far:
function callImages(){
//create the image div
$('.artslider').append('<div class="image"></div>');
//create the files array
var files = [];
//start the loop, starting position will have to be updated as images are added
for (i=8;i>=0;i--){
//create the img src for a jpg img
var imgJPG = 'arts/'+i+'.jpg';
//find the natural width of the image after it loads to see if it actually exists
var imgWidth = $('imgJPG').load().naturalWidth;
//if the width is undefined, replace the jpg extension with gif
if (imgWidth===undefined){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
//otherwise keep the jpg extension
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}
//then add the images to the img div
$('.image').append(files[i]);
}
};
The problem with this if/else is that it will only create a gif image. If you switch the order, it will only create a jpg image.
edit: here's what this code produces: https://googledrive.com/host/0B1lNgklCWTGwV1N5cWNlNUJqMzg/index.html
The problem is with this bit of code:
var imgJPG = 'arts/'+i+'.jpg';
var imgWidth = $('imgJPG').load().naturalWidth;
imgWidth will always be undefined.
Firstly you are passing in the string 'imgJPG' instead of the parameter imgJPG. Secondly I think you have misunderstood jQuery selectors, this is used for selecting HTML elements, inputting a file path into here will not achieve anything. Thirdly I think you have misunderstood the load function, this is used for loading data from the server into a HTML element.
I would suggest using a function like below to check if the image exists:
function urlExists(url) {
var http = jQuery.ajax({
type:"HEAD",
url: url,
async: false
});
return http.status == 200;
}
Then in your code:
if (!urlExists(imgJPG)){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}

Javascript to classify files as images

I have a url in javascript, set as a variable. Like:
var imageurl='example.com/test/real/image.jpg';
I am trying to recognize if this is an image url or not (ending with jpeg, jpg, gif, png etc.).
I tried using charAt but it did not work.
What's the best way to return a 1 if it is an image url and 0 otherwise using javascript?
I am trying to recognize if this is an image url or not (ending with jpeg, jpg, gif, png etc.).
The file extension (if there even is one) has no bearing on whether a URL points to a resource that is an image type. That is only a convention used by some people for static resources.
Looking at the file extension can be enough if you only need it as a general heuristic:
// User browser's built-in URL parsing to discard query string etc
//
var a= document.createElement('a');
a.href= url;
var ext= a.pathname.split('.').pop().toLowerCase();
var mightbeimage= ext=='gif' || ext=='jpeg' || ext=='jpg' || ext=='png';
but for accuracy the only way to find out if a URL points to an image is to fetch that URL and see what comes back. Typically you'd do that by issuing a HEAD request to the URL and seeing if the headers in the response contain Content-Type: image/something.
You can't do that directly from browser JavaScript, but what you can do is create an image element and see if loads OK:
function checkImage(url, callback) {
var img= new Image();
img.onload= function() { callback(true); }
img.onerror= function() { callback(false); }
img.src= url;
}
checkImage('http://www.google.co.uk/images/srpr/logo3w.png', function(isimage) {
if (isimage)
alert('Yes, it is an image');
else
alert('Nope, not an image, or does not exist or other error');
});
here you go:
var imageurl = 'example.com/test/real/image.jpg';
ext = imageurl.split('.').reverse()[0];
if (['jpg','gif','png'].indexOf(ext.toLowerCase()) > -1) {
console.log('true!');
} else {
console.log('false!');
}
If you're just after a way of figuring out things from the string, try using the following:
var imageurl = "some.gif";
imageurl.match("(?:png|jpe?g|gif)$");
// returns ['gif']
It's not a particularly complete or elegant solution, but it works.
Use lastIndexOf and substring to get the file extension and compare that to the different image types you are interested in.
try:
var fileName = "'example.com/test/real/image.jpg'";
alert(fileName.substring(fileName.lastIndexOf('.') + 1));
you get your file extension.As per condition manipulate it.

Load image... when time is eating up

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.

Categories