Library/HTML/JQuery Automatic Thumbnails

From Athile

Jump to:navigation, search


After creating the blender model, I started looking into what an ideal asset management system might look like.  I used this as an excuse to spend some time with Python 3.1 and JQuery. A python script runs on the server to generate some JSON indices for the website, then client side uses JQuery to present some user-friendly browsing and searching.

In any case, I have to say JQuery is fantastic.  It takes short amount of time to get used using "$" as your global do-everything variable, but once past that, the simplicity and flexibility of JQuery really starts to take off. == First Attempt at a JQuery Plug-in == I haven't looked into how to properly package up a "formal" JQuery plug-in, but I did write a bit of Javascript which I believe qualifies as a plug-in. The goal of the plug-in was to automatically generate an image thumbnail for an asset.  I wanted to do this on the client side for the simplicity of not having to maintain a separate cached thumbnail file.  I was willing to put up with the trade-off of the full-size image being loaded and relying on the browser's built-in image rescaling algorithm. Here's what I came up with which works fairly nicely on Chrome on Windows (admittedly the only browser I tested): '''Update''': Warning - this code snippet should be calling JQuery each() and looping over the elements of ''this''.   It also should not use $ directly.  See the JQuery plug-in standards.

Update 2: Warning - this does not work properly on all browsers as the load callback is not always called if the image is coming directly from the cache.

jQuery.fn.makeThumb = function(dim) {
  // Minimal sanity checking
  if (!this.is("img"))
    throw "Expected makeThumb call on an <img> element";
 
  // Provide a default of 192 px if no dimension is given
  if (typeof dim != "number")
    dim = 192;
 
  // Hide the image until the resizing is done to avoid
  // resizing flicker
  this.hide();
 
  // Wait for the image to load (so the width & height will
  // be accurate) then resize using CSS.  Of course the full
  // image is in memory and the rescaling algorithm is up to
  // the browser - but this is a decent way to generate thumbs
  // without any cached files.
  //
  this.load(function() {
    var w = parseInt( $(this).width() );
    var h = parseInt( $(this).height() );
    if (w < dim || h < dim) {
      var scale = (w &gt; h) ? (dim / w) : (dim / h);
      $(this).css("width", (w * scale) + "px");
      $(this).css("height", (h * scale) + "px");
    }
    $(this).show();
  });
  return this;
}

Subsequently if to make all <img /> elements with the CSS class "thumb" into 192x192 thumbnails, the simple JQuery method call $(".thumb").makeThumb(192) can be made.

(Note: please feel free to use the above trivial code snippet as if it were your own; there is no need for permission, attribution, etc.)

Navigation
Toolbox