how to know size of the image by it url - javascript

I have an input text field where the user provides the source url of the image ,
for example http://mysite/images/STARTPAGE_LOGO.gif is a valid value.
I dont have any img tag or something else in my html document. How can i determine the dimensions of the image which is present at the URL the user has entered .

There is no method to find out the width and height of the image without loading it so you will have to dynamically load it , and to do so you can use
function getDimensions(_src,_callback){
/* create a new image , not linked anywhere in document */
var img = document.createElement('img');
/* set the source of the image to what u want */
img.src=_src;
/* Wait the image to load and when its so call the callback function */
/* If you want the actual natural dimensions of the image use naturalWidth and natural height instead */
img.onload = function () { _callback(img.width,img.height) };
}
After declaring the above function in pure javascript spirit you can do something like
getDimensions('http://mysite/images/STARTPAGE_LOGO.gif',function(w,h){
console.log( "Height : ",h,"Width:",w);
});

HTML:
<input id="src" type="text" value="https://www.google.pl/images/srpr/logo3w.png"/>
JAVASCRIPT:
var img = new Image; // create tmp image element
// is equal to document.createElement('img');
Bind function on onload event, it will be called automatically when image is loaded.
img.onload = function(){
alert( this.width +" : " + this.height );
};
Set the source of image;
img.src = document.getElementById('src').value // get the value of input element;
for curiosity in jQuery:
$('<img/>').attr('src',$('#src').val()).bind('load',function(){
alert( this.width +' x ' + this.height );
});

Related

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.

How to save image width and height from onload?

I have an array of <li> elements that I am trying to make into a carousel, just that I want the images to be resized if bigger than 640x480 as well as centered into the frame.
I have the following code:
HTML:
<ul id="carousel">
<li><img src="pic1.jpg" /><p><b>2012</b> something</p></li>
<li><img src="pic2.jpg" /><p><b>2016</b> something else.</p></li>
</ul>
JQuery:
var imW=[];
var imH=[];
//...
$('li',obj).each(function(index){
itemSources.push( $(this).find('img').attr('src') );
var img = $(this).find('img');
imW.push(img.width());
imH.push(img.height());
});
I then use itemSources[i], imW[i] and imH[i] to resize my image and add any necessary padding to center it in the frame.
Which works fine provided that my internet is fast enough and the images load before the size is computed. (ha!)
I know I want something like:
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
};
img.src = $(this).find('img').attr('src');
But I cannot save the width and height, since just pushing to the arrays gets out of scope, and so does creating an external callback for that. How can I save those sizes that are so easily printed to the console into my imW and imH arrays?
You can basically set an attribute of an image, something like data-loaded="true" once the image is loaded and when the last image is loaded you can then iterate the images and load the array
In your onload method, do the following changes
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
//set this attribute to indicate that this image has been loaded already
$(this).attr( "data-loaded", "true" );
//check if all images have this attribute
if ( $( "img[data-loaded='true']" ).size() == $( "img" ).size() )
{
//now iterate the images to load your array
}
};
img.src = $(this).find('img').attr('src');

Variable values aren't available for use after image.onload?

I'm using Canvas to perform a couple of things on an image which is loaded/drawn using image.onload & context.drawImage combo. I'm calculating the bounding size for scaling the images using a simple function which returns the values. I need those values for use at a later point in my code, but no matter what I do, I'm not able to assign the values to a variable. I'm also not able to access my Canvas's styleheight/stylewidth attributes after I assign it the calculated dimensions.
Here's a pseudos ample of my code
$(document).ready(function(){
//Canvas access, context reference etc here.
//Since I'm assigning styles to the canvas on the fly, the canvas has no ht/wdt yet
var dimes = '';
var image = new Image();
image.onload = function(){
//Apply original image height/width as canvas height/width 'attributes'
//(so that I can save the original sized image)
//Check if the image is larger than the parent container
//Calculate bounds if not
//Apply calculated dimensions as 'style' height/width to the canvas, so that the image fits
dimes = scaleImage(...);
//Works!
console.log(dimes);
//Rest all code
}
image.src = '...';
//Blank!!!
console.log(dimes);
//These all blank as well!!!
jQuery('#mycanvas').height() / width() / css('height') / css('width');
document.getElementById(canvas).style.height / .style.width / height / width;
});
I need to access the calculated dimensions for a 'reset' kind of function, that resets my canvas with the drawn image to the calculated size.
As #apsillers noted, the console.log(dimes) code is being executed after you simply define the image.onload() event handler.
If you want to access dimes outside of image.onload(), you'll need to ensure it's being executed after the image loads... e.g. as a response to a button click.
Put the var dimes = ""; before the $(document).ready() to make it a global variable.
Then if you need to access dimes in an event handler, it's ready for you:
$(document).ready(function() {
var image = new Image();
var dimes = "";
image.onload = function() {
dimes = scaleImage(...);
};
$(button).click(function() {
if (dimes === "") {
// image is not yet loaded
} else {
console.log(dimes);
}
});
});
Of course, dimes will now only be accessible inside this first $(document).ready() event handler. If you add another one (which you can certainly do in jQuery), you'll need to use the $.fn.data() jQuery object method to store dimes:
$(document).ready(function() {
var image;
$(document).data("dimes", ""); // initializes it
image.onload = function() {
$(document).data("dimes", scaleImage(...));
};
});
// some other code
$(document).ready(function() {
$("#myButton").click(function() {
var dimes = $(document).data("dimes");
if (dimes === "") {
// image not yet loaded
} else {
console.log(dimes);
}
});
});
Your img.onload function can run only after the JavaScript execution thread stops being busy, i.e., after your ready function completes. Thus, your console.log(dimes) call is running before your onload function.
Put any code that needs to use dimes inside of the onload function. Otherwise, the code the needs to use dimes might run before the onload handler fires.
http://jsfiddle.net/KxTny/1/
$(document).ready(function(){
var dimes = 0;
var width = 20;
var height = 30;
pass(dimes, width, height);
});​
function pass(dimes, width, height) {
alert(dimes);
alert(height);
alert(width);
}

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];
}

How can I find out the width of an image that hasn't been styled in JavaScript (in IE)?

Imagine you have the following
img = document.createElement("img");
img.src = "MahImage.jpg";
x.appendChild(img);
What can I do to find out the Width and Height of the image without using jQuery?
I am currently using .width , which works fine for any intelligent browser, but I have to find out a way to make IE happy
After image load's you can access to properties width and height.
For example:
alert(img.height + img.width);
Also you can get image dimensions using properties clientHeight and clienWidth
To know if image loaded use onload hanler.
For example
img = document.createElement("img");
img.src = "MahImage.jpg";
img.onload = imageproperties;
x.appendChild(img);
function imageproperties() {
alert(img.height + img.width);
}
You can access the width and height properties of the image, but they will only return a useful value once the image has loaded; so you'll only want to access them inside the onload event of the image (or give it a reasonable time to load).
img = document.createElement("img");
img.onload = function () {
this.height;
this.width;
};
img.src = "MahImage.jpg";
x.appendChild(img);
You can see this working here: http://jsfiddle.net/aS7a7/
This is tricky because you cant find the height/width of an image until after it is done loading. This means you'll need a callback attached to the load of the image:
var img = document.createElement("img");
img.src = "MahImage.jpg";
img.onload = imageReady;
x.appendChild(img);
var imageReady = function() {
alert(img.height);
alert(img.width);
}
You need to wait until the image will be loaded. Here is the code (tested in Chrome):
img = document.createElement("img");
img.src = "http://google.ru/logos/2011/Albert_Szent_Gyorgyi-2011-hp.jpg";
img.onload = function(){
console.log(img.width, img.height);
}
document.getElementsByTagName('body')[0].appendChild(img);

Categories

Resources