Checking for existence of thumbnails and images - javascript

I am attempting to write some javascript in a page that needs to load one of three images. First it needs to check to see if a Thumbnail for a picture exists and display that, if the thumbnail does not exist, check for the full_size image and display that (scaled down) and if neither a thumbnail or a full-size image exists, use a noimage.gif as a small placeholder. What would be the most efficient way to do this?
Some stipulations, can't do it server side as there is no server. This java script is going to be inserted into a kml file as a . I am mapping a fiber network and this is for the hand-hole portion. Basically, each placemark will have any where from 1 to 5 pics and the names of the pics will be the same as the placemark name with a -1, -2, -3, etc. after each picture. So each of these placemarks gets its style from the same balloonstyle.... and the html I have written in this balloon style calls img src="./images/$[name]-1.jpg" width="120px" height="100px" where $[name] inserts the name of the placemark. This will allow for the users, when they update the kml file and add new placemarks, all they will have to do is rename the jpeg to match the placemark's name and add a -1 to the end of it and dump it in the images folder.... making it so the user doesn't have to edit ANY html (which is too much for them to do)

I would do the checking on the server, then have the server provide a resource path to the available image.

I agree with #Jason Dean,
But If you want to detect it by using JavaScript I would do like so:
When getting the thumbnail I would attach some kind of id/class property to it and check if it's present.
Check if id of "img-tumb" exists:
var imgThumb = document.getElementById("img-thumb");
if (imgThumb != null){
alert("Thumbnail exists");
}else{
//Check Image size...
Now to check the image size:(Placed after else of last if)
var img = document.getElementById('your_image_id');
var height = img.clientHeight;
var width = img.clientWidth;
To change the height after the image height was detected:
img.style.height = height-50;//Substracks 50 pixles from the original size
img.style.width = width-50;//Substracks 50 pixles from the original size
For you finale event(when none are detected), I would use the same checking as in phase one.
Complete code:
var imgThumb = document.getElementById("img-thumb");
var imgFull = document.getElementById("img-full");//Full sized image
if (imgThumb != null){
alert("Thumbnail exists");
}else if(imgFull != null){
//Check Image size...
alert("Full sized image exists");
var img = document.getElementById('your_image_id');
var height = img.clientHeight;
var width = img.clientWidth;
img.style.height = height-50;//Substracks 50 pixles from the original size
img.style.width = width-50;//Substracks 50 pixles from the original size
}else{
//Place noimage.gif
}

Related

How to view an image file's dimension with javascript

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.

image not getting clipped in chrome extension

What I have here is that I am saving the source dataURL of images from content script in the storage and retrieving them in the extension script.
I created each image tag with unique ID of the iterating value.
Then i created a DIV dag and appended the image tag in it.
Problem is that the images are very large in terms of length X breadth and I need to clip them to appropriate size according to the height and width parameter which was retrieved from storage.
When I apply the css property of clipping a rectangle with appropriate values, nothing happens. The image remains of the same size.
Here is the screenshot depicting the same.
As you can see in the screenshot on the right side is showing the size of the div as 1351 X 672 whereas the property of clipping has been applied with size 1321 X 137.
And also the max-height and max-width applied on the div is also not working.
Please help me strip out the extra part of the image.
extension script:
$(document).ready(function() {
chrome.storage.local.get("list",function(data){
var list=data.list;
for(var i=0;i<list.length;i++) {
//---------extract some important data stored in the storage----------
var src=list[i].src;
var note=list[i].note;
var height=list[i].height;
var width=list[i].width;
//--------------creating image tag-----------
var img=document.createElement("img");
img.setAttribute("id","myimg");
img.setAttribute("src",src);
img.setAttribute("id",i);
var div=document.createElement("div");
div.appendChild(img);
div.setAttribute("max-height","300px");
div.setAttribute("max-width","500px");
div.style.overflow="scroll";
$("body").append(div);
$("#"+i).css("clip","rect(0px,"+width+"px,"+height+"px,0px)");
}
});
});

Display image after file input selection with image resize

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]);
}

Get image dimensions after resizing

I have encountered a problem that other people had in this website before but none of the solutions helped me slightly.
I have a method that updates an image inside a div (read: user uploads a new image) where the image is resized to fit the set proportions (max-height and max-width are 45x45). I have to resize the div that holds the image to 2* it's dimensions such as the example below:
Original image is 180x180.
It is resized to 45x45. Div has to be 90x90.
Code is as follows:
function uploadThumbnail(id, xCoord, yCoord) {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("thumbnailLoader"+id).files[0]);
oFReader.onload = function(oFREvent) {
var mapThumbnail = updateMapThumbnail(oFREvent.target.result, id);
var mapContainer = document.getElementById("thumbnail"+id);
var informationContainer = document.getElementById("container"+id);
console.log(mapThumbnail.width);
mapContainer.removeChild(document.getElementById("mapThumbnail"+id));
informationContainer.removeChild(document.getElementById("infoThumbnail"+id));
informationContainer.insertBefore(updateInfoThumbnail(oFREvent.target.result, id), informationContainer.firstChild);
mapContainer.appendChild(mapThumbnail);
};
};
function updateMapThumbnail(result, id){
var newThumbnail = document.createElement("img");
newThumbnail.src = result;
newThumbnail.style.maxWidth = "45px";
newThumbnail.style.maxHeight = "45px";
newThumbnail.id = "mapThumbnail" + id;
return newThumbnail;
}
As you can see I added a console.log method there for test purposes. The problem I am facing is that generating mapThumbnail with set max dimensions (45x45) still has the height and width attributes set with the original image size. I tried reading image.height/width and image.style.height/width as well as naturalHeight/width and clientHeight/width.
None of these solutions return the height and width after resizing.
Thanks for your time.
Also, please refrain from offering solutions that require JavaScript libraries.
Edit: forgot to mention that the image placed inside the div is re-sized to the dimensions that I do want it to be. It's just the attributes that seem to be wrong.
There are four different and undependant widths on an image:
1) img.naturalWidth is the width in px the original image file has. It doesn't change when you set the other widths to some value. This value is rendered when the others are not defined.
2) img.width is an attribute of img. You find it inside the html img tag and can set it with img.setAttribute('width', 'value'). It doesn't change when the others are set to some value. This value is rendered when 3) is not defined and 4) is >= img.width or not defined.
3) img.style.width is a css-property of the images style. You can set it in your css or into the style-attribute in the img tag with img.style.width = 'value';. It doesn't change when the others are set to some value. This value is rendered when it is <= 4) or 4) is not defined.
4) img.style.max-width is another css-property of images style. You can set it in your css or into the style-attribute in the img tag with img.style.maxWidth = 'value';. It doesn't change when the others are set to some value. This is rendered when 2) or 3) are not defined or have values > 4).
So you have to decide by yourself which value you want to receive or set.
Its the same with height, there are also four heights.
EDIT According to your comment:
Inside your function updateMapThumbnail you create a new img. A newly created img has no .width unless you define it with newThumbnail.setAttribute('width', 'value). Same with img.style.width: unless you set it explicitely somewhere it's simply not there.
Did you try:
console.log(getComputedStyle(mapThumbnail).width);

Sizing/stretching images to dimensions known only after page load

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);
}
}
});

Categories

Resources