I have JS which resize the width and height of Image which is working fine if I used Alert before assigning the actual image src to the image object and if I omit the alertbox, it is not working. Please suggest me how to fix it.
`
<html>
<head>
<script type="text/javascript" language="javascript">
function resize_image_height_weight(id, hgt, wdth)
{
//alert(id);
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
// alert("Height=>" + heights + " Width=> " + widths);
if(heights > hgt || widths > wdth)
{
if(heights > widths)
{
var temp = heights/hgt;
var new_width = widths / temp;
new_width = parseInt(new_width);
heights = hgt;
widths = new_width;
}
else
{
var temp = widths/wdth;
var new_height = heights / temp;
new_height = parseInt(new_height);
heights = new_height;
widths = wdth;
}
}
Obj.height = heights;
Obj.width = widths;
}
</script>
</head>
<body>
<div>
<center>
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" id="i" alt="Google logo" height="150" width="150">
<script type="text/javascript">
document.images[document.images.length-1].onload = resize_image_height_weight("i",150,150);
</script>
</center>
</div>
</body>
</html>`
When you set the .src on an image, you have to wait until the image is successfully loaded until you can read it's height and width. There is an onload event handler that will tell you when the image is loaded.
Here's a place in your code where this issue could occur:
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
In this case, since the image was already elsewhere in the document, you should just read the height and width off the existing element rather than the new element.
Be very careful when testing because if the image is in your browser cache, it may load immediately, but when it's not in your cache, it takes some time to load and won't be available immediately.
Putting an alert at the right place in your script can allow the image to load before the script proceeds which could explain why it works with the alert.
As RobG mentions, your onload handler is also faulty (needs to be a function, not the returned result of a function).
Here's a simpler function to scale an image to fit the bounds. This uses a trick that you only need to set one size (height or width on the image) and the other will be scaled by the browser to preserve the aspect ratio.
function resizeImage(id, maxHeight, maxWidth) {
// assumes the image is already loaded
// assume no height and width is being forced on it yet
var img = document.getElementById(id);
var height = img.height || 0;
var width = img.width || 0;
if (height > maxHeight || width > maxWidth) {
var aspect = height / width;
var maxAspect = maxHeight / maxWidth;
if (aspect > maxAspect) {
img.style.height = maxHeight + "px";
} else {
img.style.width = maxWidth + "px";
}
}
}
You can see it in action here: http://jsfiddle.net/jfriend00/BeJg4/.
In the function assigned to onload:
> document.images[document.images.length-1].onload =
> resize_image_height_weight("i",150,150);
you are assigning the result of calling resize_image_height_weight which throws an error in IE. Set it to a function instead:
document.images[document.images.length-1].onload = function() {
resize_image_height_weight("i",150,150);
};
Related
I am currently running into a problem with my code. I am attempting to set the height of an image through JavaScript in a check that its less than 600 pixels. I have tried a plethora of alternatives to the general "this.height = 600" but none have resulted successfully. I am really hoping someone can help me fix this problem.
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
<script>
function setImage() {
var img = new Image();
var images = [
"bean.jpg",
"xxx-edit-parallax/Images/xxx-5.jpg"
];
var chosen = images[Math.floor(Math.random() * images.length)];
img.onload = function(){
if (this.height > 600) {
console.log("more than");
this.height = 600;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
}
};
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
}
</script>
It successfully passes the "if" but never actually sets the height.
EDIT: Unaware of the CSS property of max-height and max-width at the time. Was brought to my attention by Lain. Thank you
It would be much easier to use the css property max-height.
Just to show the actual flaw with the approach in javascript: you have to pass the height on to the actual image. Currently you merely set it to the img object yet never to the shown image <img src="" id="cursedimg">.
var img = new Image();
var images = ['https://logosmarken.com/wp-content/uploads/2018/05/Google-Logo.png'];
var maxHeight = 200; //REM: For my test image
img.onload = function(){
if (this.height > maxHeight) {
console.log("more than");
this.height = maxHeight;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
};
//REM: Here you need to assign the src along with the height
document.getElementById("cursedimg").src = this.src;
document.getElementById("cursedimg").style.height = this.height + 'px';
};
//REM: No need for toString() - it already is.
img.src = images[Math.floor(Math.random() * images.length)];
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
Even easier would be to not create a new object at all and just assign it as is:
var img = document.getElementById("cursedimg");
By running the following code, you are assigning the only the src attribute to the img element
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
If you want to set the height and src of the image element using javascript,
you can do the following:
var image = document.getElementById("cursedimg");
if ( image.height > 600 ){
image.height = 600;
}
else{
image.style.height = "auto"; // since 'auto' is a styling value
}
image.src = chosen.toString();
I'm using this plugin to create image zoom and gallery, yet I want to scale all images to fit with the container (using ratio algorithm).
Here is ratio function :
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
And this is how the gallery load images :
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
What I've tried :
var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
But scaleSize is not working properly since the current width and height is not yet defined (image not yet exist in dom).
Thanks for any pointers.
I took a look into plugin code and think you call your scaleSize() too early. An image with class simpleLens-big-image exists first after var img is set up and addClass() is done.
Try following:
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Try something like this and call the onload method. This will make sure that the image is loaded to the DOM before you resize
var img = $('<img>');
img.src = src ;
img.onload = function() {
// Run onload code.
} ;
My application has a large size of images to present and which should be resized for uniformly presentation with fixed width and height, to do so I write a JavaScript method in image's onload image like this:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcHeight = targetHeight;
calcWidth = (targetHeight / height) * width;
} else {
calcWidth = targetWidth;
calcHeight = (targetWidth / width) * height;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
HTML image:
<img src='PATH' onload='autoResizeImage(100, 100, this)'>
This way works well on Chrome and Firefox except IE 6,7,8. I'm suffering on this, how can I complete this task on IE 6,7,8.
Thanks so much.
I would start by saying that if you're serving images to be displayed at a particular size, you should send them from the server at the correct size in the first place. Sending excessively large images and having the browser resize them is poor practice because it means that you're using up a lot more bandwidth than you need to. Your users may have restricted bandwidth, and may not appreciate the extra load time on your page caused by this.
However, I don't really know why you need to do this resizing exersise at all? HTML will by default scale an image to the size of the <img> tag that contains it anyway, so all you need to do is specify height and width styles for your <img> tag, and the scaling will be done automatically. There should be absolutely no need for all that messing around with Javascript.
<img src='PATH' style='width:100px; height:100px;'>
That should work in all browsers; no JS required. The image should be scaled for you.
But ideally, as I said, please try to avoid sending excessively large images to the page if you're not going to use them at full size.
Change the order of assignments. First assign onload function and then src attribute. It works for IE 8 at least.
var div = document.getElementById('div');
var img = new Image();
img.onload = function() {
var text = document.createTextNode('loaded ' + img.src);
div.appendChild(text);
};
window.setTimeout(function() {
var random = Math.random();
img.src ="http://stackoverflow.com/users/flair/450989.png?random=" + random;
}, 1000);
div.appendChild(img);
<div id="div"/>
I'm trying to load an image from a given link
var imgPath = $(imgLink).attr('href');
and append it to the page, so I can insert it into a given element for an image viewer.
Even though I searched Stackoverflow and the jQuery docs without end, I can't figure it out.
After I load the image, I want to set different values to it, like width, height, etc.
Update:
This is what I got. The problem I'm having is that I can't run jQuery functions on the img element.
function imagePostition(imgLink) {
// Load the image we want to display from the given <a> link
// Load the image path form the link
var imgPath = $(imgLink).attr('href');
// Add image to html
$('<img src="'+ imgPath +'" class="original">').load(function() {
$(imgLink).append(this);
var img = this;
// Resize the image to the window width
// http://stackoverflow.com/questions/1143517/jquery-resizing-image
var maxWidth = $(window).width(); // window width
var maxHeight = $(window).height(); // window height
var imgWidth = img.width; // image width
var imgHeight = img.height; // image height
var ratio = 0; // resize ration
var topPosition = 0; // top image position
var leftPostition = 0; // left image postiton
// calculate image dimension
if (imgWidth > maxWidth) {
ratio = imgHeight / imgWidth;
imgWidth = maxWidth;
imgHeight = (maxWidth * ratio);
}
else if (imgHeight > maxHeight) {
ratio = imgWidth / imgHeight;
imgWidth = (maxHeight * ratio);
imgHeight = maxHeight;
}
// calculate image position
// check if the window is larger than the image
// y position
if(maxHeight > imgHeight) {
topPosition = (maxHeight / 2) - (imgHeight / 2);
}
// x position
if(maxWidth > imgWidth) {
leftPostition = (maxWidth / 2) - (imgWidth / 2);
}
$(imgLink).append(img);
// Set absolute image position
img.css("top", topPosition);
img.css("left", leftPostition);
// Set image width and height
img.attr('width', imgWidth);
img.attr('height', imgHeight);
// Add backdrop
$('body').prepend('<div id="backdrop"></div>');
// Set backdrop size
$("#backdrop").css("width", maxWidth);
$("#backdrop").css("height", maxHeight);
// reveal image
img.animate({opacity: 1}, 100)
img.show()
});
};
$('<img src="'+ imgPath +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
If you want to do for several images then:
function loadImage(path, width, height, target) {
$('<img src="'+ path +'">').load(function() {
$(this).width(width).height(height).appendTo(target);
});
}
Use:
loadImage(imgPath, 800, 800, '#some_target');
Here is the code I use when I want to preload images before appending them to the page.
It is also important to check if the image is already loaded from the cache (for IE).
//create image to preload:
var imgPreload = new Image();
$(imgPreload).attr({
src: photoUrl
});
//check if the image is already loaded (cached):
if (imgPreload.complete || imgPreload.readyState === 4) {
//image loaded:
//your code here to insert image into page
} else {
//go fetch the image:
$(imgPreload).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
} else {
//image loaded:
//your code here to insert image into page
}
});
}
var img = new Image();
$(img).load(function(){
$('.container').append($(this));
}).attr({
src: someRemoteImage
}).error(function(){
//do something if image cannot load
});
after you get the image path, try either of following ways
(as you need to set more attr than just the src)
build the html and replace to the target region
$('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
you may need to add some delay if changing the "SRC" attr
setTimeout(function(){///this function fire after 1ms delay
$('#target_img_tag_id').attr('src',imgPaht);
}, 1);
I imagine that you define your image something like this:
<img id="image_portrait" src="" alt="chef etat" width="120" height="135" />
You can simply load/update image for this tag and chage/set atts (width,height):
var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
With jQuery 3.x use something like:
$('<img src="'+ imgPath +'">').on('load', function() {
$(this).width(some).height(some).appendTo('#some_target');
});
This is what I need:
The image must completely fill 100% the area the div covers - left to
right and top to bottom.
the image must not be squashed or streched - just be cropped or
must overflow.
The image must be kept as small as possible, so whatever the resize - you
can still see either the very sides OR the very top and bottom.
The div itself will be adjusting in height and width as both are a percentage of the main window.
I have found a little bit of JavaScript here that is manipulating the image just how I want when the window is resized, but is displaying it in the whole window.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var height_ratio = image_height / window_height
var width_ratio = image_width / window_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<img onload="resizeImage()" src="f/a.jpg">
</body>
</html>
Here is a demo
Please don't just answer that all I need is:
<img style="width : 100%;">
This is so much more than that.
It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Can it (or something like it) be made to work the same way within a % sized div?
I wrote a jQuery plugin that does exactly this. Check out my blog post here and the demo here
jQuery.fn.resizeToParent = function(options) {
var defaults = {
parent: 'div'
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = jQuery(this);
// bind to load of image
obj.load(function() {
// dimensions of the parent
var parentWidth = obj.parents(o.parent).width();
var parentHeight = obj.parents(o.parent).height();
// dimensions of the image
var imageWidth = obj.width();
var imageHeight = obj.height();
// step 1 - calculate the percentage difference between image width and container width
var diff = imageWidth / parentWidth;
// step 2 - if height divided by difference is smaller than container height, resize by height. otherwise resize by width
if ((imageHeight / diff) < parentHeight) {
obj.css({'width': 'auto', 'height': parentHeight});
// set image variables to new dimensions
imageWidth = imageWidth / (imageHeight / parentHeight);
imageHeight = parentHeight;
}
else {
obj.css({'height': 'auto', 'width': parentWidth});
// set image variables to new dimensions
imageWidth = parentWidth;
imageHeight = imageHeight / diff;
}
// step 3 - center image in container
var leftOffset = (imageWidth - parentWidth) / -2;
var topOffset = (imageHeight - parentHeight) / -2;
obj.css({'left': leftOffset, 'top': topOffset});
});
// force ie to run the load function if the image is cached
if (this.complete) {
obj.trigger('load');
}
});
}
And if you want the image to resize when the window is resized, just bind a resize handler to the window:
$(window).resize(function() {
$('img').resizeToParent();
});
Ok I've been playing around with it:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
It keeps resizing as the div resizes - as mentioned the div is
resizing with the window - this one keeps working seemlesly.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and safari
over xp and 7
so really it answers my question perfectly, its just - now i've seen Christian's centering version i wish i had the know-how to make this do it i've tried a few things but am now stuck. Any Ideas?
P.S. if you dont know the width and height % of the div when you right the script i think it could be got with GetElementById - somehow... beyond me though;)