Sizing/stretching images to dimensions known only after page load - javascript

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

Related

How can I load an image before it's needed?

I'm developing a website with an image gallery. There is a grid of images with dozens of thumbnails. When a user clicks on an image a div slides down from the top. That div's CSS gets edited with JavaScript to change the background-image.
My problem is that the div slides down, but the background image "flickers" in randomly. What I want is the div to slide down with the image already loaded. I'm not sure how to solve this problem because I think it would be unreasonable to pre-load every thumbnail's larger version when the user most likely won't click on them all.
You can convert the image to base64 and enable it in src of the img tag, after that send in the dormulário.
this use example: https://hdtuto.com/article/how-to-convert-image-into-base64-string-jquery
One way to preload images is to create an image object using javascript
Here's an example:
HTML:
<img src="photo1.jpg" id="photo" />
Javascript:
var photo = document.getElementById("photo");
var loadImage = new Image();
loadImage.src = "YourSrc/image.jpg";
Last step, use this code in your event handler when you want to change to the preloaded image:
photo.src = loadImage.src;
If you are looking to preload multiple images use an array and a loop.
imageSrcs = ["imgsrc1.jpg", "imgsrc2jpg", "imgsrc3jpg"];
preloadedImages = [];
for(var i = 0; i < imgSrcs.length; i++)
{
preloadedImages[i] = new Image();
preloadedImages[i].src = preloadedImages[i];
}

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

Javascript - Image change an resize to full background

As a quick explanation, I created an image that resizes to fill the background using this function which works great:
function resize_bg(element_id){
$("#"+element_id).css("left","0");
var doc_width = $(window).width();
var doc_height = $(window).height();
var image_width = $("#"+element_id).width();
var image_height = $("#"+element_id).height();
var image_ratio = image_width/image_height;
var new_width = doc_width;
var new_height = Math.round(new_width/image_ratio);
if(new_height<doc_height){
new_height = doc_height;
new_width = Math.round(new_height*image_ratio);
var width_offset = Math.round((new_width-doc_width)/2);
$("#"+element_id).css("left","-"+width_offset+"px");
}
$("#"+element_id).width(new_width);
$("#"+element_id).height(new_height);
return true;
}
So no problem for the full background image. The problem appears, when I change the image source using Javascript. In other words, I have 1 image set as background but on hover of certain elements on the page, the image changes but it doesn't change the resize right. So the first image on load is resized and positioned correctly, but when I switch the image using .attr('src',newimg) the image is not resized correctly even though I call the function again.
Here is the code I use to change the image and resize it:
$('#menu_work li a').hover(function(){
$('#content').hide();
var img_src = $(this).next('img').attr('src');
$('#full_screen_img').attr('src', img_src );
resize_bg();
$('#full_screen_img').show();
},function(){
$('#full_screen_img').hide();
$('#content').show();
});
Thanks for any help.
It appears that you have left out the element_id argument when calling resize_bg() in the hover event handler. As a result, resize_bg() can't find the element you want to resize.
#maxedison is right, you forgot to pass the element id.
Another problem is that when you change the src, the new image might not be loaded yet, so you won't get the right dimensions in resize_bg until it is.
In that case you'll need to resize the image once it's loaded:
$('#full_screen_img').attr('src', img_src ).load(function() {
resize_bg('<ELEMENT_ID>');
});
resize_bg('<ELEMENT_ID>');
On another note, I'd recommend you change resize_bg to get a jQuery object instead of an id, or even write a plugin ($.fn.resize_bg) if it's a functionality you want to use often.

Checking for existence of thumbnails and images

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
}

JavaScript Image Loading

When I am click on a button then a javascript function is invoked and it loads the image in the page. But the image is not loading properly. The image size is 72kb and the image coming from the DB and it's already loaded in the server start.
If I put any alert message then the image loads properly. What's the reason behind the issue?
var catImg = document.getElementById(\"CategorySampleImage\");
var oldImgSrc = catImg.src;
var newImgSrc = oldImgSrc.substr(0,oldImgSrc.indexOf(\"images\"))+\"images/\"+\""+imageName+"\";
catImg.src=newImgSrc;
for (var intCounter = 1; intCounter <= 500; intCounter++){
for (var counter = 1; counter <= 500; counter++)
{
if(counter==500)
break;
}
}
document.getElementById(\"light\").style.display=\"block\";
document.getElementById(\"fade\").style.display=\"block\";";
code works fine for all browsers except IE6. In IE6 I can see a white area in place of the Image and I need to right click on theat white area and select “Show Image”. But a smaller image in the same div displays correctly. Don't know how could I solve this issue on IE6.
You can use onload event on the image object when loading it to make sure that it is already loaded.
Ex.
catImg.onload = function(){ /* Image is loaded. Do something here*/ }

Categories

Resources