views:

2516

answers:

4

In an HTML window, I am setting a custom body

<img src="file://[filename]">

to display an image.

Now I want to strectch the image to fit the available window, but preserve aspect ratio.

<img src="file://[filename]" width="100%" height="100">

stretches but also distorts the image.

Is there some HTML trickery to do that? IE only solution is fine, since this is in a hosted broweser control.

A: 

Pure HTML no.

This could be done in JavaScript if you know the aspect ratio of the image. Don't know if that is possible via JS though, but you could pass that value to the JavaScript if you are using any other language as well.

Ólafur Waage
+1  A: 

Nope, you're going to have to use Javascript for this, and it's trickier than it sounds. I did something similar the other week, here;s the function I created for it, you might be able to re-appropriate it

Oh, and it needs jQuery

function resize_background(){

    var target = $("#background_image");
    var window = $(window);
    var ratio = 1;
    var anchor_point = 200;
    var register_point = 400;

    if(window.width() > min_width){
     ratio = window.width() / min_width;
     target.css("marginLeft", 0);
    }else{
     // center to screen
     // For this project, this aint needed.
     //var left_margin = (window.width() / 2) - (min_width / 2);
     //target.css("marginLeft", left_margin);
    }

    // now figure out anchor stuff
    var top = ((register_point * ratio) - anchor_point) * -1;

    target.width(min_width * ratio);
    target.height(min_height * ratio);
    target.css("marginTop", top);

    $("#trace").text(top);


}
gargantaun
+5  A: 

If you know either the height or width, you can set only that. The other dimension will be automatically set based on the aspect ratio of the image.

tgecho
oh... yeah, that as well.
gargantaun
This may cut off the picture in the other axis. e.g. having "width=100%"´for an image with AR 1:2 in an AR 1:1 window, the lower half is cut off.
peterchen
+1  A: 

If you want to preserve aspect ratio, you only need to specify one dimension ie:

<img src="file://[filename]" width="100%" alt="" />

You can use javascript to determine max dimension and resize accordingly

<script type="text/javascript">
function getImgSize(id){
var pic = document.getElementById(id);
var h = pic.offsetHeight;
var w = pic.offsetWidth;
alert ('The image size is '+w+'*'+h);
}
</script>
Philippe
How do I put that into a resize handler, and hoew do I get the size of the window?
peterchen
I've ended up convincing the guys that "width="100%"" is "good enough".
peterchen