CSS value of a image using JavaScript - javascript

I have a image on the website.
i should get the CSS value of Max_width for that image using java script for my Jasmine framework.
Can you please guid me.
Here is the code:
it("Should return Max-width value: '"+width+"'",function(){
var width, item;
item = OpenSpace.getElementById("OpenLayers.Layer.Vector_49_svgRoot");
width = item.max_width;
expect(result).toBe(width);
alert(width);
Thanks
Ravi

clientWidth is the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.
var img = document.getElementById('imageid');
var width = img.clientWidth;
Another solution:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
Hope it works

Related

jQuery - How do I get the image width of an online image?

I have a project which consists of a HTML, JS and CSS file.
When I open the project in my browser I have an input field (url input), a button and a canvas.
After I insert the URL of an image in the input field and click the button, I want the canvas to resize according to the width and height of the image. Of course, I also want the image to be displayed in the canvas.
Note: Later I want to add a functionality where someone can resize the image with a slider. This means that I really have to save the width of the image in a variable.
So, my main problem is that I don't know how to get the width of that image.
The last thing I tried is the following:
$('#btn_load').click(function () {
input_url = $('#input_url');
var url = input_url.val();
var img_width = url.width;
...
});
Would be glad about some help here, since I tried a lot of stuff in the last hours :)
EDIT:
I now also tried the following:
var inputURL, imgWidth;
inputURL = $('#input_url');
$('#btn_load').click(function () {
var url = inputURL.val();
var img = new Image();
img.src = url;
img.onload = function () {
imgWidth = img.width;
};
canvas.css({
'background-image': 'url(' + url + ')',
//'background-size': 'cover',
});
//This is just to check the width value
inputURL.val(imgWidth + url);
});
But still doesn't work.
This will get the img width and height in the global variables 'imgHeight' and 'imgWidth' It will also display the image on the screen, width a slider to make it bigger or smaller,
the min and max value of the input type range are dynamically set to the original width and height divider by 2 or for the maximum multiplied by 2.
Javascript:
var imgHeight;
var imgWidth;
var img = new Image();
function LoadImage() {
input_url = $('#input_url');
img.src = input_url.val();
//img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
//alert(imgHeight + " : " + imgWidth);
//Now set the image to html
document.getElementById("imgID").src=img.src;
//Now set the dimensions.
$("#imgID").css({'height' : imgHeight+'px', 'width' : imgWidth+'px'});
//Now set the range min to imgwidth / 2. and the max to imgwidth * 2
document.getElementById("range").min = imgWidth / 2;
document.getElementById("range").max = imgWidth * 2;
document.getElementById("range").value = imgWidth;
}
}
function ChangeImageSize(value) {
//Calculate new height so the image doesn't get stretched.
newHeight = value / imgWidth * imgHeight;
//Set the new width and height
$("#imgID").css({'height' : newHeight+'px', 'width' : value+'px'});
}
HTML
<button onclick="LoadImage()">click me</button>
<input type="range" id="range" oninput="ChangeImageSize(this.value)">
<input type="text" id="input_url">
<img id="imgID">
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" > </script>
<script>
function loadUrl() {
//You can get the value of your url_input and use it instead.
var url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"; //You can take it from your input_url
$("#img-size").attr("src", url);
};
function imageLoaded(sender){
alert($(sender).width() + 'x' + $(sender).height());
}
</script>
</head>
<body>
<img src="" id="img-size" onload="imageLoaded(this);">
<input type="button" onclick="loadUrl();" id="btn_load" value="Load" />
</body>
</html>
You should load the imag to get its natural width and height :
var img = new Image();
img.src = $('#input_url').val();
img.onload = function () {
imageWidth= img.naturalWidth;
imageHeight = img.naturalHeight;
...
}

Get Image Dimensions (Height and Width) Js or jquery

I have searched for this, but every time I implement the code it return 24 as height and width as 237 when I upload 400X400 image.
$(document).on('change','#tt' , function(){
var img = document.getElementById('tt');
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
alert(nheight)
alert(nwidth)
});
<input type="file" id="tt" name="tt" >
Is anyone know how can I get 400 as height and 400 as width in alert box when I upload 400X400 image. Any help is really much appreciated.....
Onchange event of file upload creating a Image object and attach uploaded file object as src to image object and then onload event of image object find height and width of image.
Please check below snippet for more understanding.
var _URL = window.URL || window.webkitURL;
$(document).on('change','#tt' , function(){
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert("width : "+this.width + " and height : " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="tt" name="tt" >
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
will just get you the dimension.
Refer this -
Try
var x = document.getElementById("myImg").naturalWidth;
the naturalHeight property to return the original height of an image, or the height property to set or return the value of the height attribute of an image
http://www.w3schools.com/jsref/prop_img_naturalwidth.asp

Javascript resize background color proportionally to its own size

I want to resize a background image 30% to its original size then use it as background to an element. I am sure my mistake is somewhere in the last line.
Here is my code :
var img = new Image();
img.src = "wallpaper.jpg";
var a = img.height;
var newWidth = (img.width*0.3));
var newHeight = (img.height*0.3));
t.getBody().style.backgroundImage = "url("+img.src+")";
t.getBody().style.backgroundSize = "(newWidth)px (newHeight)px";
Values of background-size property should be like Xpx Ypx. Try change Your last line to this:
t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";
substitute the newWidth and newHeight values with a space in between.
var img = new Image();
img.src = "wallpaper.jpg";
var a = img.height;
var newWidth = (parseInt(img.width)*0.3);
var newHeight = (parseInt(img.height)*0.3);
t.getBody().style.backgroundImage = "url("+img.src+")";
t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";

getting image width and height from input:files multiple [duplicate]

I have a Base64 image encoded that you can find here. How can I get the height and the width of it?
var i = new Image();
i.onload = function(){
alert(i.width + ", " + i.height);
};
i.src = imageData;
For synchronous use just wrap it into a promise like this:
function getImageDimensions(file) {
return new Promise (function (resolved, rejected) {
var i = new Image()
i.onload = function(){
resolved({w: i.width, h: i.height})
};
i.src = file
})
}
then you can use await to get the data in synchronous coding style:
var dimensions = await getImageDimensions(file)
I found that using .naturalWidth and .naturalHeight had the best results.
const img = new Image();
img.src = 'https://via.placeholder.com/350x150';
img.onload = function() {
const imgWidth = img.naturalWidth;
const imgHeight = img.naturalHeight;
console.log('imgWidth: ', imgWidth);
console.log('imgHeight: ', imgHeight);
};
Documentation:
HTMLImageElement.naturalWidth
HTMLImageElement.naturalHeight
This is only supported in modern browsers. NaturalWidth and NaturalHeight in IE
A more modern solution is to use HTMLImageElement.decode() instead of the onload event. decode() returns a promise and thus can be used synchronously with await.
Asynchronous use:
let img = new Image();
img.src = "myImage.png";
img.decode().then(() => {
let width = img.width;
let height = img.height;
// Do something with dimensions
});
Synchronous use (inside an async function):
let img = new Image();
img.src = "myImage.png";
await img.decode();
let width = img.width;
let height = img.height;
// Do something with dimensions
Create a hidden <img> with that image and then use jQuery's .width() and . height()
$("body").append("<img id='hiddenImage' src='" + imageData + "' />");
var width = $('#hiddenImage').width();
var height = $('#hiddenImage').height();
$('#hiddenImage').remove();
alert("width:" + width + " height:" + height);
Test here: JSFiddle
The image is not initially created hidden. It gets created, and then you get width and height and then remove it. This may cause a very short visibility in large images. In this case, you have to wrap the image in another container and make that container hidden, not the image itself.
Another Fiddle that does not add to the DOM as per gp.'s answer:
here

Get image width and height from the Base64 code in JavaScript

I have a Base64 image encoded that you can find here. How can I get the height and the width of it?
var i = new Image();
i.onload = function(){
alert(i.width + ", " + i.height);
};
i.src = imageData;
For synchronous use just wrap it into a promise like this:
function getImageDimensions(file) {
return new Promise (function (resolved, rejected) {
var i = new Image()
i.onload = function(){
resolved({w: i.width, h: i.height})
};
i.src = file
})
}
then you can use await to get the data in synchronous coding style:
var dimensions = await getImageDimensions(file)
I found that using .naturalWidth and .naturalHeight had the best results.
const img = new Image();
img.src = 'https://via.placeholder.com/350x150';
img.onload = function() {
const imgWidth = img.naturalWidth;
const imgHeight = img.naturalHeight;
console.log('imgWidth: ', imgWidth);
console.log('imgHeight: ', imgHeight);
};
Documentation:
HTMLImageElement.naturalWidth
HTMLImageElement.naturalHeight
This is only supported in modern browsers. NaturalWidth and NaturalHeight in IE
A more modern solution is to use HTMLImageElement.decode() instead of the onload event. decode() returns a promise and thus can be used synchronously with await.
Asynchronous use:
let img = new Image();
img.src = "myImage.png";
img.decode().then(() => {
let width = img.width;
let height = img.height;
// Do something with dimensions
});
Synchronous use (inside an async function):
let img = new Image();
img.src = "myImage.png";
await img.decode();
let width = img.width;
let height = img.height;
// Do something with dimensions
Create a hidden <img> with that image and then use jQuery's .width() and . height()
$("body").append("<img id='hiddenImage' src='" + imageData + "' />");
var width = $('#hiddenImage').width();
var height = $('#hiddenImage').height();
$('#hiddenImage').remove();
alert("width:" + width + " height:" + height);
Test here: JSFiddle
The image is not initially created hidden. It gets created, and then you get width and height and then remove it. This may cause a very short visibility in large images. In this case, you have to wrap the image in another container and make that container hidden, not the image itself.
Another Fiddle that does not add to the DOM as per gp.'s answer:
here

Categories