It seems simple, by using the “max-width” propery through CSS, however; IE6 doesn’t support it.
Here’s a simple “hack” to get it working, by using expressions (in javascript-like syntax) in CSS, that IE6 does support.
.my_img {
max-width: 500px;
/* Resize the image for IE6 */
width: expression(this.width > 500 ? 500: true);
}
The code above is simple CSS, that will work for all major browsers to set a maximum width for an image (in this case: 500px).
All you need to do now is set the class on your image:
<img class="my_img" src="my-image.jpg" alt="" />
There are, of course, alternatives as well. You could call a javascript function that will determine the width of your image, and resize accordingly. Here’s the function.
function resizePhoto() {
if (document.getElementById('photo_id')) {
photo = document.getElementById('photo_id');
if (photo.width > 500) {
photo.width = 500;
}
}
}
And at the bottom of your page, you could activate it by:
<script type="text/javascript">
resizePhoto();
</script>
Again, this has a downside. Javascript can only resize your image, if it was loaded at the time you called the resizePhoto() function. You could solve this by preloading your images in javascript, or by using setTimeout() to call the same function a few seconds later (when you “guess” the image has loaded by then).
<script type="text/javascript">
resizePhoto();
setTimeout(resizePhoto, 3000);
setTimeout(resizePhoto, 6000);
setTimeout(resizePhoto, 9000);
</script>
This’ll try to resize the image right away, after 3 seconds, 6 and 9 seconds. If the image is already resized, these functions won’t do anything any more – so we can safely call them after each other.
The CSS style is probably the “cleanest”, and should be preferred. If for some reason you can’t use this, know that there are a ton of alternatives to be used – including javascript. You could also use the GDLibrary in PHP to analyse the image, and add the necessary “width='500′ " tags if the image exceeds certain sizes.