Javascript get width of img from path - javascript

i think there should be an easy solution for this, but I can't figure it out.
What I'm trying to do is to get the width/height of an image by its path (not rendered on screen).
Like:
var img = ImageInfo(path);
alert(img.width);
(I want to do this in plain javascript)

You can do something like this:
function getImageSize(imgSrc) {
var imgLoader = new Image(); // create a new image object
imgLoader.onload = function() { // assign onload handler
var height = imgLoader.height;
var width = imgLoader.width;
alert ('Image size: '+width+'x'+height);
}
imgLoader.src = imgSrc; // set the image source
}
You basically create a new image using javascript. Assign the onload event, and then set the source and wait for image to load. when it's loaded the onload handler alerts the height and width of the image. check this jsFiddle

Let ImageInfo function to accept a callback(ie: make it async).
function ImageInfo(path, onLoad) {
var img = new Image();
img.src = path;
img.onload = function() {
onLoad(img);
}
}
Use it like:
ImageInfo(url, function(img) {
alert(img.width);
});

Try this:
var path = "http://images2.wikia.nocookie.net/__cb20110928222437/callofduty/images/4/4f/Personal_IW_FTW_Awesome_Face_100px.png";
var img = new Image();
img.src = path;
It's pretty simplified, but something alone these lines should work.
http://jsfiddle.net/s9QVp/1/

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.

Why JavaScript code execute second part sometimes

I am draw background on canvas and also small images on that background. But sometimes, background draw on small images. Why ?
JavaScript code -
var canvasupdate = document.getElementById("myCanvas");
ctxupdate = canvasupdate.getContext("2d");
var background = new Image();
background.src = sitePath + "ATOM/chapter1/book/" + `bgimagename`;
background.onload = function() {
ctxupdate.drawImage(background, 0, 0); // set background image
};
var imageobj = new Array();
for (var d = 0; d < calloutImageArray.length; d++) // getting small images in array
{
imageobj[d] = new Image();
(function(d) {
imageobj[d].src = sitePath + "ATOM/chapter1/book/" + calloutImageArray[d];
imageobj[d].onload = function() {
ctxupdate.drawImage(imageobj[d], calloutImageArrayX[d], calloutImageArrayY[d], calloutImageArrayW[d], calloutImageArrayH[d]);
};
})(d);
}
In above code, background image code should be execute first then call out image(small image) code execute but some time execute small images code and then background image code why?
All the images are loaded asynchronously. So sometimes the small images are loaded (and drawn) before the background image. Please take a look into e.g. Network tab in Chrome in which order the resources load is done.
The simplest solution for this problem is to move the loading of small images into the callback function for load event of the background image.
The onLoad function runs asynchronously. That means JavaScript will continue to run the rest of your code and will run the callback function when the background image is loaded. That's why your second part of the code runs first. So instead try to add your code inside the onload function like this:
var canvasupdate = document.getElementById("myCanvas");
ctxupdate = canvasupdate.getContext("2d");
var background = new Image();
background.src = sitePath + "ATOM/chapter1/book/" + `bgimagename`;
background.onload = function() {
ctxupdate.drawImage(background, 0, 0); // set background image
var imageobj = new Array();
for (var d = 0; d < calloutImageArray.length; d++) // getting small images in array
{
imageobj[d] = new Image();
(function(d) {
imageobj[d].src = sitePath + "ATOM/chapter1/book/" + calloutImageArray[d];
imageobj[d].onload = function() {
ctxupdate.drawImage(imageobj[d], calloutImageArrayX[d], calloutImageArrayY[d], calloutImageArrayW[d], calloutImageArrayH[d]);
};
})(d);
}
};
that way you can be sure that the background will be set first and then your small images. Note that I didn't try your code to check if it does what you want, I just rearranged the code blocks to show you the logic and why does not run as you would expect.
Hope it helps

Is this an efficient way to display an image using jQuery

This code works, but is it an efficient way to go about displaying an image once it has been loaded?
LightBoxNamespace.SetupLightBox = function(path, lightBox) {
// Create a new image.
var image = new Image();
// The onload function must come before we set the image's src, see link for explanation.
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.
// Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
image.onload = function () {
if ($('#image').length) {
$('#image').attr('src', path); // If the element already exists, change the src to our loaded image.
}
else {
$('<img id="image" alt="">').attr('src', path).insertAfter('#close'); // If the element does not exist, insert the full image html into the lightbox.
}
LightBoxNamespace.CentreBoxInViewport(lightBox);
LightBoxNamespace.ShowOverlay(lightBox);
};
// Set the src, and show the image.
image.src = path;
};
var img = $('<img>');
img.load(function(){alert("image loaded!")});
img.attr('src', "url");
if (!! img) img.appendTo('#close');
http://jsfiddle.net/W57QR/4/
"The jQuery way":
var $img = $('<img/>').prop({ src: path });
$img.load(function() {
console.log('image loaded correctly');
$(this).insertAfter('#close');
}).error(function() {
console.log('error loading image');
});

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