JavaScript - function to get real image width & height
javascriptTo get the real width and height of an image using JavaScript, you can create a new Image object and set the src property to the URL of the image. You can then use the onload event to execute a function that retrieves the image’s natural width and height.
Here’s an example:
function getImageSize(imageUrl, callback) {
var img = new Image();
img.src = imageUrl;
img.onload = function() {
callback({
width: img.naturalWidth,
height: img.naturalHeight
});
};
}
In this example, we define a function called getImageSize that takes two parameters: imageUrl, which is the URL of the image to retrieve the size of, and callback, which is a function to execute once the image has loaded and its size has been determined.
Inside the function, we create a new Image object and set its src property to the URL of the image. We then set the onload event to a function that retrieves the image’s natural width and height using the naturalWidth and naturalHeight properties of the img object. We then pass an object containing the width and height properties to the callback function.
To use the getImageSize function, you can call it with the URL of the image and a function to handle the result:
getImageSize('path/to/image.jpg', function(size) {
console.log(size.width + ' x ' + size.height);
});
In this example, we call the getImageSize function with the URL of the image and a function that logs the width and height of the image to the console. When the image has loaded and its size has been determined, the callback function is executed with an object containing the width and height properties.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame