I'm trying to assign variables that store the height and width of an image from the local "img" folder. I tried something along the lines of
myWidth = (("img/myImage.png").naturalWidth);
but as far as I can tell, that only works if the image is already present somewhere on the page. Is there a way to do this by getting Javascript to view the file's properties in the folder?
EDIT: I'm not doing anything too technical. I just have 600 or so small images that need to be in separate divs that are the same pixel width and height as the image, and each image is different. I'm trying to write a script to generate all the code for my css without having to type it all in manually.
You can use an Image element to get the dimensions. I have previously created a tool that fetches image dimensions via JavaScript for an SO question. You can see it in action here: https://codepen.io/NikxDa/pen/apegZa
Necessary part:
var img = new Image ();
// Handle onload (will contain data after file has loaded)
img.onload = function () {
alert ("The dimensions are: " + this.width + "x" + this.height);
};
// Load the file by fileUrl
img.src = <fileUrl>;
Hope it helps.
Related
I want to make an image previewer inside a page. I will have a "div" to include smaller images by setting the size of "img" by hand. Then clicked or hovered, the image will show on a bigger "div", as small as the image itself or as big as window view size near the mouse pointer. the code will have only image link and will get actual image size from there.
setting the size and position of previewer "div" is just a mathematical problem for me. but I can't seem to find how to get image size by the link. I tried only to get mostly undefined values if not errors.
Be careful while answering that most of the thought methods get the size from the "img" element itself if sizes are set, but returns null if not.
CAUTION: this is similar to How to get image size (height & width) using JavaScript? , but (a) accepted answer does not work for me. it gives either 0x0 or undefined. (b) suggested answer of Josh Stodola works only if image loaded with window. my link is dynamic.
this is also similar to Get width height of remote image from url. It works with alert function, but I cant get the size out of the said functions as I need them for calculations.
I updated my answer. It now triggers on a mouseover event and doesn't use an ID. Be sure to accept the answer if this is working for you.
function getMeta(imageSrc,callback) {
var img = new Image();
img.src = imageSrc;
img.onload = function() { callback(this.width, this.height); }
}
function hoverLink(imageSrc){
getMeta(
imageSrc,
function(width, height) {
document.getElementById("prev").innerHTML = width + 'px ' + height + 'px';
}
);
}
function hoverOff(){
document.getElementById("prev").innerHTML ='';
}
<a href="https://res.cloudinary.com/rss81/image/upload/gw.jpg"
onmouseover="hoverLink(this.href)"
onmouseout="hoverOff()">
Picture Link
</a>
<div id='prev'></div>
Thanks to #dcr, I got the problem over. He helped me with the code, and I have seen the problem that confused me.
Those answers to other posts mostly used "alert" function, which is not a good way to show how to get required value, in my case the size of an image.
Here in this code, it can clearly be seen that "getMeta" and "caller" functions are merely an interface to "setter". I can reference any required value from "callback" part and "setter" can then be expanded to the needs, in my case calculating the size and position of my previewer "div". The only difference with #dcr 's solution is getting the "setter" function out of "caller" function.
function getMeta(imageSrc,callback) {
var img = new Image();
img.src = imageSrc;
img.onload = function() { callback(this.width, this.height); }
}
function caller(imageSrc){
getMeta( imageSrc,setter);
}
function setter(width, height) {
document.getElementById("prev").innerHTML = width + 'px X ' + height + 'px';
}
Picture Link
<div id='prev'></div>
I have seen posts asking how to display an image selected via a file input control. When I try these solutions, they work, yet I have a further issue I am unable to discover an answer to on my own: When I select an image for the first time, the image will not display because no image width and height data is available (image data is available via the FileReader obj, yet not the image width and height). The second time the image is selected (or after a reload), the width and height become available. Why is this occurring and what can I do to fix it? thanks.
Here's some code I've been using - this is one of the FileReader functions. I started by using reader.onload, but then thought the image width and height were not available because it hadn't loaded fully yet. Therefore onloadend seemed a better choice. It doesn't work any better here, though:
reader.onloadend = function(e) {
var img = new Image();
img.src = e.target.result;// or reader.result - doesn't matter
// A function that does math to proportionally scale the image
var new_size = scaleImageSize(150, 150, img.width, img.height);
img.width = new_size[0];
img.height = new_size[1];
// And here I am trying both ways to display the image: the first
// in a div tag, the second straight into an img tag. I only want
// to use one of these - preferably the div tag. I have also tried
// drawing the image onto an HTML5 canvas. All to no avail.
document.getElementById("file_display_area").appendChild(img);
document.getElementById("img_file_display_area").src = img.src;
console.log(img.width + '|' + img.height + '||' + new_size[0] + '|' + new_size[1]);
}
This question already has answers here:
jQuery event for images loaded
(14 answers)
Closed 8 years ago.
I want to create a picture preview plugin and for this i want to create a dynamic bar under the preview image with a title and so on
The Images have no consistent width so I need to adjust the bar everytime I select a new Picture.
The preview Image source is also created dynamicly with the source path of the clicked image but another directory.
To adjust the bar i ask for the preview image's width: var width = $("#maximized_image").width(); and I call this directly after I set the source of the preview image.
But my problem is that sometimes apparently the image is loaded after the width is defined so my width is 0 and my bar is not visible. Is it possible to wait for the image is loaded or force jquery to wait for it?
Or does anyone have another solution?
EDIT:
Here is what I have till now:
var img = $(this).attr("src");
var img_split = img.split('.');
var img_path = img_split[0];
var rest = img_path.substring(0, img_path.lastIndexOf("/") + 1);
var last = img_path.substring(img_path.lastIndexOf("/") + 1, img_path.length);
var max_image = rest + "/normal/" + last + "." + img_split[1];
$("#image_maximizer").css("height", win_h).css("width", "100%").css("display", "block").css("background", "rgba(0, 0, 0, 0.6)");
$("#render_img").attr("src", max_image);
var width = $("#maximized_image").width();
alert(width);
this sets the image but i don't get the image's width
you can load the image but render it off screen, get the width then load it where you need it (you wont be loading it twice as its already loaded/cached)
I'd suggest though that you load the image THEN load in the bar with a nice fade effect or something, I'm sure a slight 300ms etc delay wont make too much difference?
Using something like onLoad for the image will say when the image is loaded but it will still have to be rendered first
Run a function when the page is fully loaded including graphics:
$( window ).load(function() {
// Run code
});
jquery load event
On my website, users can upload large images. I display these images like this:
<img id="userImage" src="userImage.ashx?width=740&id=4fc265d4-a83c-4069-8d6d-0fc78ae2840d">
userImage.ashx is a handler that returns image files based on id, so in this example the image for user 4fc265d4-a83c-4069-8d6d-0fc78ae2840d is returned. You can also set other attributes - in this example only width is given. The image is resized so that it is 740px wide.
I set the src of the image in javascript, once the rest of the page has loaded. By doing this I know how wide the image has to be to fill all the available space:
var width = document.getElementById("userImageHolder").getComputedSize().width;
document.getElementById("userImage").src = "flash/userImage.ashx?type=micrositePhoto&id=" + userId + "&width=" + width;
This all works, but the image doesn't load until everything else on the page has loaded. I have a complex solution to a simple problem.
Is there a better way to do this? What is the best way to shrink/stretch images to fill an area that is only known once the page loads?
Figure out what the upper limit is for width and height and generate the image to that size, then use max-width/max-height to allow the browser to auto scale it based on the size of the browser window.
Try to preload your images in a onDOMReady handler, and then insert in an onLoad one. While this can't guarantee the images to be loaded before everything else, they can at least start loading earlier.
Someting like this (using jQuery):
$(document).ready(function(){
var imageArray = [],
imageSrc = [];
//Fill image src array from somewhere
var len = imageSrc.length;
for(var i = 0; i < len; i++){
var img = new Image();
img.src = imageSrc[i];
img.onload = function(){
//Do something with your loaded image
imageArray.push(this);
}
}
});
Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time?
I've looked into this "CSS Spriting" technique but I don't think I can use that here. The source image is produced dynamically from the server; I won't know the total length, or the size of each frame, until it comes back from the server. I'm hoping that I can do something like:
var image = getElementByID('some-id');
image.src = pathToReallyLongImage;
// Any way to do this?!
image.width = cellWidth;
image.offset = cellWidth * imageNumber;
This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set position: relative and overflow: hidden on it. Absolutely position your image inside of it and change the position to change which portions are displayed.
To display a 30x40 section of an image starting at (10,20):
<style type="text/css">
div.viewport {
overflow: hidden;
position: relative;
}
img.clipped {
display: block;
position: absolute;
}
</style>
<script type="text/javascript">
function setViewport(img, x, y, width, height) {
img.style.left = "-" + x + "px";
img.style.top = "-" + y + "px";
if (width !== undefined) {
img.parentNode.style.width = width + "px";
img.parentNode.style.height = height + "px";
}
}
setViewport(document.getElementsByTagName("img")[0], 10, 20, 30, 40);
</script>
<div class="viewport">
<img class="clipped" src="/images/clipped.png" alt="Clipped image"/>
</div>
The common CSS properties are associated with classes so that you can have multiple viewports / clipped images on your page. The setViewport(…) function can be called at any time to change what part of the image is displayed.
In answer to :
Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML element combined with a bit of server-side scripting.
...
< ? (open php)
$large_image = 'path/to/large_image';
$full_w = imagesx($large_image);
$full_h = imagesy($large_image);
(close php) ? >
This can be done in Javascript, just google a bit :
var newimage = new Image();
newimage.src = document.getElementById('background').src;
var height = newimage.height;
var width = newimage.width;
This generates a new image from an existing one and captures this way in java script the original height and width properties of the original image (not the one id'ed as background.
In answer to :
The width/height properties of the document's image object are read only. If you could change them, however, you would only squish the frames, not cut the frames up like you desire. The kind of image manipulation you want can not be done with client-side javascript. I suggest cutting the images up on the server, or overlay a div on the image to hide the parts you do not wish to display.
...
var newimage = new Image();
newimage.src = document.getElementById('background').src;
var height = newimage.height;
var width = newimage.width;
newimage.style.height = '200px';
newimage.style.width = '200px';
newimage.height = '200px';
newimage.width = '200px';
and if wanted :
newimage.setAttribute('height','200px');
The doubled newimage.style.height and newimage.height is needed in certain circumstances in order to make sure that a IE will understand in time that the image is resized (you are going to render the thing immediately after, and the internal IE processing is too slow for that.)
Thanks for the above script I altered and implemented on http://morethanvoice.net/m1/reader13.php (right click menu... mouseover zoom lent) correct even in IE , but as you will notice the on mousemove image processing is too fast for the old styled IE, renders the position but only once the image. In any case any good idea is welcome.
Thanks to all for your attention, hope that the above codes can help someone...
Claudio Klemp
http://morethanvoice.net/m1/reader13.php
CSS also defines a style for clipping. See the clip property in the CSS specs.
The width/height properties of the document's image object are read only. If you could change them, however, you would only squish the frames, not cut the frames up like you desire. The kind of image manipulation you want can not be done with client-side javascript. I suggest cutting the images up on the server, or overlay a div on the image to hide the parts you do not wish to display.
What spriting does is essentially position a absolutely-positioned DIV inside another DIV that has overflow:hidden. You can do the same, all you need to do is resize the outer DIV depending on the size of each frame of the larger image. You can do that in code easily.
You can just set the inner DIV's style:
left: (your x-position = 0 or a negative integer * frame width)px
Most JavaScript Frameworks make this quite easy.
Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML <canvas> element combined with a bit of server-side scripting.
PHP code to go about extracting the width and height of the really large image:
<?php
$large_image = 'path/to/large_image';
$full_w = imagesx($large_image);
$full_h = imagesy($large_image);
?>
From here, you'd then load the image into a <canvas> element, an example of which is documented here. Now, my theory was that you may be able to extract pixel data from a <canvas> element; assuming that you can, you would simply make sure to have some form of definite divider between the frames of the large image and then search for it within the canvas. Let's say you found the divider 110 pixels from the left of the image; you would then know that each "frame" was 110 pixels wide, and you've already got the full width stored in a PHP variable, so deciphering how much image you're working with would be a breeze.
The only speculative aspect to this method is whether or not JavaScript is capable of extracting color data from a specified location within an image loaded into a <canvas> element; if this is possible, then what you're trying to accomplish is entirely feasible.
I suppose you want to take a thumbnail for your image. You can use ImageThumbnail.js that created from prototype library in this way:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="ImageThumbnail.js"></script>
<input type="file" id="photo">
<img src="empty.gif" id="thumbnail" width="80" height="0">
<script type="text/javascript">
<!--
new Image.Thumbnail('thumbnail', 'photo');
//-->
</script>
for more information
try use haxcv library haxcv js by simple functions
go to https://docs.haxcv.org/Methods/cutImage to read more about his library
var Pixels = _("img").cutImage (x , y , width , height );
_("img").src (Pixels.src);
// return cut image
but try to include library first