javascript - Get height of image from url on Chrome - javascript

I am working with height of image in javascript,
my code:
<script>
var linkBg = 'http://imageshack.us/a/img24/5489/2013042200001.jpg';
var bgimg = new Image();
bgimg.src = linkBg;
var bgHeight = bgimg.height;
alert(bgHeight);
</script>
my problem is: when I run this script on Firefox, it return the height of images, but on Chrome it return 0.
How can I fix this problem using only javascript without Jquery, thanks for any help !

You need to wait until image is fully loaded , like this:
var imgHeight , imgWidth;
bgimg.onload = function() {
imgHeight = bgimg.naturalHeight;
imgWidth = bgimg.naturalWidth;
}

Related

Loading image delayed display after loaded

So I have this html / css / jQuery / js code that toghether shows a VERY large image in width. The base element should be invisible untill the image is loaded and set. Then the base element is made visible by a small fade.
However the behaviour is a little different.
Once the image is being loaded i can see the small text fading in and it takes a few seconds before then the image just pops up in once (not loading style like from top to bottom appearing)
This is the simplified code i use:
<script>
$(function() {
$("#base").hide();
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').fadeIn(500);
};
img.src = backLayerSRC;
});
</script>
<style>
#base {
position:absolute;
left:0px;
height:100%;
}
#base #img {
position:absolute;
left:0px;
top:0px;
}
</style>
<div id='base'>
some tekst
<img src='' id='img' data-src='path_to_very_large/image.png' />
</div>
Now, how could it be that it just doesn't fade in WITH the image?
Here is an example WITH the image, please check so it becomse clear what i mean
http://jsfiddle.net/uz8mvtap/3
It might depend on the time the browser needs to render the image after the script loaded it.
I played a little with your fiddle and came up with this:
$(function() {
$("#base").css({opacity: 0});
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').delay(1000).animate({opacity: 1.0},500);
};
img.src = backLayerSRC;
});
Basically using opacity for such a purpose is better because #base continues to occupy the same space, not disrupting the page. And the delay is for the browser, I figured for a big image it takes time to render, so let's give it it.
You could do that.
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
After it loads, it summons a callback, use that callback to do custom function. Let me know how it goes.
or, by the way. You could enter image width and image height into custom var, and compare them on the load, once it reaches your wanted width and height, fade it in.
You seem to be slightly misinterpreting the timeline of your code:
Page loads, (text is visible on screen)
jQuery kicks in, hides #base (text is not visible on screen)
jQuery fades in #base (text is visible on screen again)
This is why you are briefly seeing the text before the image loads - because it is not initially hidden.
Add:
display: none;
To your #base style, add keep the rest of your code the same.
Also I've created an alternative JavaScript solution after you have added the above CSS:
$(function() {
const base = $("#base"),
img = $("#img"),
backLayerSRC = img.attr('data-src'),
baseHeight = $('#base').height();
img.attr('src', backLayerSRC);
img.one("load", () => {
img.height(baseHeight).promise().done(() => { base.fadeIn(2500); });
});
});
Here is the working example of your code I have created:
https://codebrace.com/editor/b16cabfee
Your baseHeight variable is undefined.
May be you should change
$('#base').height(baseHeight);
to
var baseHeight = $('#base').height();
Update:
I have updated the solution. I this solution I have wrapped div around both the text and image. Div wrapped around image is set to position:relative; to keep the image(set to absolute position) from covering the text.
https://codebrace.com/editor/b16f33afb

Jquery height resize not working on mobile

I'm using jquery to resize an image on a mobile website: http://www.loiristorantino.com.br/mobile
On browser, if you resize your screen, it works fine but on mobile it's not working. Here's the code that I'm using:
var $inner = $('.inner');
var height = parseInt($inner.height()) + parseInt($inner.css('top'));
$('.tumb-img-border').css('height', height);
var doit;
function resizedw(){
var $inner = $('.inner');
var height = parseInt($inner.height()) + parseInt($inner.css('top'));
$('.tumb-img-border').css('height', height);
}
window.onresize = function() {
clearTimeout(doit);
doit = setTimeout(function() {
resizedw();
fontResuze();
}, 100);
};
I think it's something related with Jquery but I don't know how to change it to javascript.
Can you guys help me with this issue?
Ok, so I found the solution by myself. Since I got this resize function on google, this solution might help others. I just changed the following line and it worked:
//var height = parseInt($inner.clientHeight());// + parseInt($inner.css('top'));
var newheight = $('.inner').height();
$('.tumb-img-border').css('height', newheight);

How to get the height of an image?

I wrote this to show me the height of an image:
alert($("img.my_pic").height());
However, it tells me that the height of an image is 0.9090919494628906, which is incorrect.
What should I do to get the correct height?
You have to wait until the image loads to the DOM
function imageSize(img){
var theImage = new Image();
$(theImage).load(function() {
var imgwidth = this.width;
var imgheight = this.height;
alert(imgwidth+'-'+imgheight);
});
theImage.src = img.attr('src');
}
jsFiddle Demo
Try
$("img.my_pic").prop('height')
The images has to be fully loaded ofcourse.
You can use the complete property to check if the image is loaded.
if ($("img.my_pic").prop('complete') === false){
$("img.my_pic").on('load', function(){
alert($(this).prop('height'));
});
}
else{
alert($("img.my_pic").prop('height'));
}
DEMO
$("img.my_pic").on('load', function() { alert( this.height ); });
This was rlemon's answer that worked for me. Since he answered it as a comment and not an answer I'm just answering this for him.

Resize HTML canvas after loading image

See http://jsfiddle.net/jdb1991/6sxke/
I've got a canvas element that doesn't know what it's going to be used for until an image has loaded, so I need to be able to change the dimensions of the element on the fly, after creating the image object.
Something is going wrong though, as it seems to be running the commands asynchronously; writing the image to the context before the resize occurs.
use:
function objectifyImage(i) {
var img_obj = new Image();
img_obj.src = i;
return img_obj;
}
var canvas = document.getElementById('display');
var context = canvas.getContext('2d');
i = objectifyImage('https://www.google.co.uk/images/srpr/logo3w.png');
i.onload = function() {
canvas.width = i.width;
canvas.height = i.height;
context.drawImage(i, 0, 0);
};
​
demo: http://jsfiddle.net/ycjCe/1/
The element can be sized arbitrarily by CSS, but during rendering the
image is scaled to fit its layout size. (If your renderings seem
distorted, try specifying your width and height attributes explicitly
in the attributes, and not with CSS.)
source: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Basic_usage
It appears i = objectifyImage will set the image src before the image.onload handler is defined. This will cause cached images to get loaded on some browsers prior to the onload definition. Its a good idea to always define onload handlers before setting the image.src to avoid timing issues with cached images.
var self = this;
.....
this.img = document.createElement('img');
this.img.onload = function () {
self.loaded = IMGSTATE_OK;
$Debug.log('loaded image:"' + self.img.src);
}
this.img.onerror = function () {
self.loaded = IMGSTATE_ERR;
$Debug.log('error image:"' + self.img.src);
}
this.img.src = href;
..... later on check the load state

Get full size of image in javascript/jquery

I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to return the current size of the image.
Images have naturalWidth and naturalHeight properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.
One would still have to wait for the image to load though
$('#idOfMyimg').on('load', function() {
var height = this.naturalHeight,
width = this.naturalWidth;
});
Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it
var img = new Image();
img.onload = function() {
var height = this.height,
width = this.width;
}
img.src = $('#idOfMyimg').attr('src');
FIDDLE
You can clone the image, remove the height and width attributes, append it to the body and get the width and size before removing it.
jsFiddle demo is here: http://jsfiddle.net/58dA2/
Code is:
$(function() {
var img = $('#kitteh'); // image selector
var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
$('#height').text(hiddenImg.height());
$('#width').text(hiddenImg.width());
hiddenImg.remove();
});​
You can do this with an Image object that holds the same source file like:
var preloader = new Image();
preloader.src = 'path/to/my/file.jpg';
preloader.onload = function(){
var height = preloader.height;
var width = preloader.width;
}
Try this:
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();

Categories