iPhoto-like image resizing using Javascript

December 7th, 2005 by John Berry

Upon seeing the Fluxiom intro video, I was compelled to figure out how they pulled off iPhoto-like image scaling in a browser. Leveraging the work of others, it’s actually very simple.

If you use the script.aculo.us slider control to capture input values, it’s really just a matter of converting those values into something useful and modifying styles.

Note: OS X folks using Firefox will likely get some stutter, due to a crippling, 3 year old bug.

A simple demo.

Here’s how.

1. Install and reference the Prototype and script.aculo.us libraries.

2. Create the track and slider HTML nodes. (CSS inline for simplification)

<div id=”track1″ style=”width: 200px; height:18px;”>
  <div id=”handle1″ style=”width: 18px; height: 18px;”>
    <img src=”/images/content/blog/scaler_slider.gif”/>

3. Create a function to be called when the slider value changes. This collects all nodes for resizing, remaps the 0-1 scale to a definable range, and then scales.

function scaleIt(v) {
  var scalePhotos = document.getElementsByClassName(‘scale-image’);

  floorSize = .26;
  ceilingSize = 1.0;
  v = floorSize + (v * (ceilingSize – floorSize));

  for (i=0; i < scalePhotos.length; i++) {
    scalePhotos[i].style.width = (v*190)+’px’;

4. Create the slider and map the two events to our function (either inline, or as part of the body onload event). See the Slider docs for usage details.

var demoSlider = new Control.Slider(‘handle1′,’track1′,
{axis:’horizontal’, minimum: 0, maximum:200, alignX: 2, increment: 2, sliderValue: 1});

demoSlider.options.onSlide = function(value){

demoSlider.options.onChange = function(value){

5. Finally, create the HTML for our images.

<div style=”border: 1px solid #ddd; width: 424px; overflow: auto;”>
  <div class=”scale-image” style=”width: 190px; padding: 10px; float: left;”>
    <img src=”/images/content/blog/scaler_1.jpg” width=”100%”/>
  <div class=”scale-image” style=”width: 190px; padding: 10px; float: left;”>
    <img src=”/images/content/blog/scaler_2.jpg” width=”100%”/>

There are definitely some areas to clean up (redundant div width specifications, for example), but for a quick demo it will suffice. Tested with Firefox, Safari and Win IE 6.

Update: There appears to be a small issue in IE; the slider disappears when you start dragging.
Update: Fixed. Moved the handle image to an actual img.
Update: Corrected a typo. (Fluxium != Fluxiom)