jQuery: how to get the dimensions of a external image? - javascript

Looking for a way to get the dimensions (width and height) of an external image. I have used prop() and attr(), but they don't return any values. Just an error.
Example:
some link

jQuery
var path = 'https://source.unsplash.com/random/600x300/?montreal';
$("<img/>").attr('src', path).load(function() {
console.log(this.width, this.height);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Vanilla Javascript
var path = 'https://source.unsplash.com/random/600x300/?montreal';
var img = new Image();
img.src = path;
img.addEventListener('load', function() {
console.log(this.width, this.height);
});

Looks like none has provided a working vanilla js answer.
var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
console.log( this.width )
console.log( this.height )
}
Here is a jsfiddle: http://jsfiddle.net/Ralt/VMfVZ/

This isn't technically jQuery but I would go down the route of:
var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;
You can then access those values using width and height, for example alert('My image is ' + width + ' pixels accross.');

Related

Take image dimensions and apply them to another image

PROBLEM: I have 2 images, one is taken from my database using src=data:image;base64,$row[2] and has given dimensions.
The other image is taken from an HTML element with ID=img00 and it is a transparent image. I need the transparent image to have the same width and height of the image taken from my database.
MY GUESS: I would like to save getMeta output to 2 variables for width and height, that I would later use instead of '200px'.
Do you believe there's a smarter way than this code?
Else, what would I have to do to save getMeta output and use it instead of that 200px?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) { alert(width + 'px ' + height + 'px') }
);
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = '200px';
img00.style.width = '200px';
}
If you want to use the values from inside getMeta, you are going to have to change the timing of the execution of the last block of code. Perhaps something like this?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
function sizeImg00(w,h){
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = h + 'px';
img00.style.width = w + 'px';
}
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) {
console.log(width + 'px ' + height + 'px');
sizeImg00(width, height);
}
);

Set div width and height using an external image?

I'm trying to get the width and height of an external image and use the width and height to set a Div's width and height in my page.
I can easily get the image width and height but I cannot use the width/height for my div for some strange reason!
To explain this better, I've created this fiddle:
https://jsfiddle.net/qtc3q6sd/2/
And this is my entire code:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", $(this.width()));
$("#mydiv").css("height", $(this.height()));
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
could someone please advise on this issue?
Thanks in advance.
You are getting the width and the height the wrong way.
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#droppable").css("width", this.width);
$("#droppable").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
See jsfiddle.
Nothing wrong with the logic of your code. just a syntax error.
it should be $(this).width() instead of $(this.width())
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", $(this).width());
$("#mydiv").css("height", $(this).height());
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
Syntax is just a bit off,
try this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#mydiv").css("width", this.width);
$("#mydiv").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
Here is your solution. Inside your callback function, this is the image
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
$("#mydiv").css("width", this.width + 'px');
$("#mydiv").css("height", this.height + 'px');
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
Your code has two mistakes.
First, inside the onload function 'this' represents the image object. You're trying to call the with() and height() functions of the image, but they're not functions, they are properties. You must lose the '()'.
Second, when you try to do this $(this.width()) you're encapsulating the width value in a jQuery object. You don't need that, just use the width property this.width.
The code below will work:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.width);
$("#mydiv").css("width", this.width);
$("#mydiv").css("height", this.height);
}
img.src = 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

How to display an image as a property in JavaScript objects

//construtor created
function Blog(text, date, image) {
this.show_image = function(src, width, height, alt){
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
}
//instance
var blog = [new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"),'show_image("images/overlay.png", 20,30, "Google Logo")'),
Hey m calling an image in above instance for that i've written a function show_image performs that part but the image is not getting displayed...please tell me what is wrong here ...please modify it...I'm new in javascript programming..
I
i have no idea why are you creating constructor and all..this can be done, with creating a simple function
try this
function show_image(src, width, height, alt){
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
$(document).ready(function(){ //if using jquery
show_image("images/overlay.png", 20,30, "Google Logo");
});
You are actually not calling the show_images function. You are just passing a string and that is not going to help.
Remember before finding out why the particular block of code is not working, you need to find out if that block is executed at all.
This is one more way you make it work.
function Blog(text, date) {
this.show_image = function (src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
}
//instance
var blog = new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"));
blog.show_image("images/overlay.png", 20,30, "Google Logo");

Loading Image into document.body Background

I'm attempting to pull an image (in this case, /camera/frame, which is a known-good JPG), and load it as the background of my document.body.
Here's my code thus far:
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
console.log("onload");
document.body.style.backgroundImage = this.src;
};
backgroundImage.src = 'camera/frame';
"onload" prints as expected, and this.src prints out the full URL to /camera/frame, however document.body.style.backgroundImage remains "".
I believe you may be missing two things.
var path = 'path/to/image.jpg';
document.body.style.background='url('+path+')';
Canvas 2D to the rescue!
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(this, 0, 0, this.width, this.height);
};
backgroundImage.src = 'camera/frame';
backgroundImage.width = $(window).width();
backgroundImage.height = $(window).height();
Loads the image in the background, then draws it into the canvas seamlessly!

Getting image width on image load fails on IE

I have a image resizer function that resize images proportional. On every image load a call this function with image and resize if its width or height is bigger than my max width and max height. I can get img.width and img.height in FF Chrome Opera Safari but IE fails. How can i handle this?
Let me explain with a piece of code.
<img src="images/img01.png" onload="window.onImageLoad(this, 120, 120)" />
function onImageLoad(img, maxWidth, maxHeight) {
var width = img.width; // Problem is in here
var height = img.height // Problem is in here
}
In my highligted lines img.width don't work on IE series.
Any suggestion?
Thanks.
Don't use width and height. Use naturalWidth and naturalHeight instead. These provide the image unscaled pixel dimensions from the image file and will work across browsers.
Man, I was looking for this for 2 days. Thanks.
I'm using jQuery, but it doesnt matter. Problem is related to javascript in IE.
My previous code:
var parentItem = $('<div/>')
.hide(); // sets display to 'none'
var childImage = $('<img/>')
.attr("src", src)
.appendTo(parentItem) // sets parent to image
.load(function(){
alert(this.width); // at this point image is not displayed, because parents display parameter is set to 'none' - IE gives you value '0'
});
This is working in FF, Opera and Safari but no IE. I was getting '0' in IE.
Workaround for me:
var parentItem = $('<div/>')
.hide();
var childImage = $('<img/>')
.attr("src", src)
.load(function(){
alert(this.width); // at this point image css display is NOT 'none' - IE gives you correct value
childImage.appendTo(parentItem); // sets parent to image
});
This is how I solved it (because it's the only js on the site I didn't want to use a library).
var imageElement = document.createElement('img');
imageElement.src = el.href; // taken from a link cuz I want it to work even with no script
imageElement.style.display = 'none';
var imageLoader = new Image();
imageLoader.src = el.href;
imageLoader.onload = function() {
loaderElement.parentElement.removeChild(loaderElement);
imageElement.style.position = 'absolute';
imageElement.style.top = '50%';
imageElement.style.left = '50%';
// here using the imageLoaders size instead of the imageElement..
imageElement.style.marginTop = '-' + (parseInt(imageLoader.height) / 2) + 'px';
imageElement.style.marginLeft = '-' + (parseInt(imageLoader.width) / 2) + 'px';
imageElement.style.display = 'block';
}
It's because IE can't calculate width and height of display: none images. Use visibility: hidden instead.
Try
function onImageLoad(img, maxWidth, maxHeight) {
var width = img.width; // Problem is in here
var height = img.height // Problem is in here
if (height==0 && img.complete){
setTimeOut(function(){onImageLoad(img, maxWidth, maxHeight);},50);
}
}
var screenW = screen.width;
var screenH = screen.height;
//alert( screenW );
function checkFotoWidth( img, maxw )
{
if( maxw==undefined)
maxw = 200;
var imgW = GetImageWidth(img.src);
var imgH = GetImageHeight(img.src);
//alert(GetImageWidth(img.src).toString()); // img.width); // objToString(img));
if (imgW > maxw || (img.style.cursor == "hand" && imgW == maxw))
{
if (imgW > screenW) winW = screenW;
else winW = imgW;
if (imgH > screenH) winH = screenH;
else winH = imgH;
img.width=maxw;
img.style.cursor = "pointer";
img.WinW = winW;
img.WinH = winH;
//alert("winW : " + img.WinW);
img.onclick = function() { openCenteredWindow("Dialogs/ZoomWin.aspx?img=" + this.src, this.WinW, this.WinH, '', 'resizable=1'); }
img.alt = "Klik voor een uitvergroting :: click to enlarge :: klicken Sie um das Bild zu vergrössern";
//alert("adding onclick);
}
}
function GetImageWidth(imgSrc)
{
var img = new Image();
img.src = imgSrc;
return img.width;
}
function GetImageHeight(imgSrc)
{
var img = new Image();
img.src = imgSrc;
return img.height;
}
I'd try this:
function onImageLoad(img, maxWidth, maxHeight) {
var width, height;
if ('currentStyle' in img) {
width = img.currentStyle.width;
height = img.currentStyle.height;
}
else {
width = img.width;
height = img.height;
}
// whatever
}
edit — and apparently if I were to try that I'd learn it doesn't work :-) OK, well "width" and "height" definitely seem to be attributes of <img> elements as far as IE is concerned. Maybe the problem is that the "load" event is firing for the element at the wrong time. To check whether that's the case, I would then try this:
function onImageLoad(img, maxWidth, maxHeight) {
var width, height;
var i = new Image();
i.onload = function() {
width = i.width; height = i.height;
// ... stuff you want to do ...
};
i.src = img.href;
}
getDisplay().getImage().setUrl(imgURL);
final Image img = new Image(imgURL);
int w=img.getWidth();
int h=img.getHeight();

Categories

Resources