Jump to content
MakeWebGames

[FAQ] How to resize an image with javascript.


Recommended Posts

Posted

I'll throw 98% of the credit for this to Spudisnki and his how to in the php how to's which does the same thing.

I thought it'd be worth noting that the same thing could be done with javascript. I even took his code and converted it to javascript format with minimal changes. The changes mostly involve removing $'s and getting the image size via the DOM instead of PHP's GD library.

His PHP FAQ is here.

Check that out for his explanation of why this is useful!

 


<html>
<head>
<title>Image Resizing!</title>
</head>
<body>
[img=bar_samp.jpg]
</body>
<head>
<script>
// use document.getElementById to get a reference to the image object in the DOM
// the image we're resizing must have an id attribute. We're using id="my-image"
var image = document.getElementById('my-image');
var config = [];
config[0] = 150;
config[1] = 150;
if (image.width > config[0] || image.height > config[1]) { // if the width or hieght is greater than the specified ones
var xr = config[0] / image.width; // specified width divided by the original width
var yr = config[1] / image.height; // specified height divided by the original height
if (xr * image.height < config[1]) { // if the height is less than the width
	image.height = Math.ceil(xr * image.height); // calculate the height, as it will be less than the width
	image.width = config[0]; // the width doesnt need any further calculation
} else { // if the width is less than the height
	image.width = Math.ceil(yr * image.width); // calculate the width, as it will be less than the height
	image.height = config[1]; // the height doesnt need any further calculation
}
}
</script>
</head>
</html>

<!-- // Ignore the php tags lol, only used for colorization... 
?>-->

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...