Accessing Image Width Outside of onload with Javascript - javascript

I am trying to use a call back to determine if an images width is correct. It seems that when using an onload that it is impossible to do a return true or false.
Should this callback work to alleviate that issue? It seems that the onload event is never firing.
validateImageSize(function(imageWidth){
alert(imageWidth);
});
function validateImageSize(callback) {
imageFile = document.getElementById("filePath").files[0];
imageFileUrl = window.URL.createObjectURL(imageFile);
uploadedImage = new Image();
uploadedImage.onload = function(){
var imageWidth = uploadedImage.width;
callback(imageWidth);
};
uploadedImage.src = imageFileUrl;
};

Related

Javascript get width of img from path

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/

How to do a process after completion of another one in JavaScript

I want to add an image by Javascript, then calculating the html element width as
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
el.innerHTML = '<img src="img.jpg" />';
var width = el.offsetWidth;
.....
}, false);
}
but since JavaScript conduct all processes simultaneously, I will get the width of the element before loading the image. How can I make sure that the image has been loaded into the content; then calculating the element width?
UPDATE: Thanks for the answers, but I think there is a misunderstanding. img src="img.jpg" /> does not exist in the DOM document. It will be added later by Javascript. Then, when trying to catch the element by Id, it is not there probably.
You can give the img an ID and do the following :-
var heavyImage = document.getElementById("my-img");//assuming your img ID is my-img
heavyImage.onload = function(){
//your code after image is fully loaded
}
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
var img = new Image();//dynamically create image
img.src = "img.jpg";//set the src
img.alt = "alt";
el.appendChild(img);//append the image to the el
img.onload = function(){
var width = el.offsetWidth;
}
}, false);
}
This is untested, but if you add the image to the DOM, set an onload/load event-handler and then assign the src of the image, the event-handling should fire (once it's loaded) and allow you to find the width.
This is imperfect, though, since if the image is loaded from the browser's cache the onload/load event may not fire at all (particularly in Chromium/Chrome, I believe, though this is from memory of a bug that may, or may not, have since been fixed).
For the chrome bug you can use the following:-
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';//create a blank source
var tImg = document.getElementById("my-img");//get the image
var origSrc = tImg.src;//get the original src
tImg.src = BLANK;//change the img src to blank.
tImg.src = origSrc;//Change it back to original src. This will lead the chrome to load the image again.
tImg.onload= function(){
//your code after the image load
}
You can use a library called PreloadJS or you can try something like this:
//Somewhere in your document loading:
loadImage(yourImage, callbackOnComplete);
function loadImage(image, callbackOnComplete){
var self = this;
if(!image.complete)
window.content.setTimeout(
function() { self.loadImage(image, callbackOnComplete)}
,1000);
else callbackOnComplete();
}
I did this when I worked with images base64 which delay on loading.

Javascript image onload not firing when loading from local file

I'm trying to give the user a preview of how an image will look when combined with another image before they upload the image (think gun shooting a bullet). I can get the image to load into an image element, but then the onload event doesn't fire (tested in chrome and firefox). I've tried using setTimeout as a dirty hack, but unfortunately bullet.image.height does not appear to be set within a relatively short space of time.
Here is an example of what I'm trying to do:
if (input.target.files && input.target.files[0]) {
var file = new FileReader();
file.onload = function (event) {
// this part works fine
var bullet = {};
bullet.id = 0;
bullet.image = new Image();
bullet.image.onload = function () {
// This never fires
bullet.offset_y = bullet.image.height / 2;
$('#modal-weapons-field-bullet').append('<option value="0">' + bullet.title + '</option>');
$('#modal-weapons-field-bullet').val(0);
};
bullet.src = event.target.result;
bullet.offset_x = 0;
bullet.title = input.target.files[0].name;
}
file.readAsDataURL(input.target.files[0]);
}
bullet.src should be bullet.image.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];
}

Categories

Resources