views:

18

answers:

1

ok, here's the deal:

I'm using a nice plugin I got from http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/

It's nice and all, but it doesn't solve a particular problem: I'll have users uploading images of differing sizes and aspect ratios, so, here's what they provided:

function preview(img, selection) { 
 var scaleX = 160 / selection.width; 
 var scaleY = 160 / selection.height; 
 $('#thumbnail + div > img').css({ 
  width: Math.round(scaleX * 500) + 'px', 
  height: Math.round(scaleY * 375) + 'px',
  marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
  marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 

where the numbers after scaleX and scaleY are the actual pixel dimensions of the image they use in their demo. I want to be able to have a user upload a pic, then have .js create vars to have those values become the scaleX and scaleY multipliers, such that:

width: Math.round(scaleX * width) + 'px', 
height: Math.round(scaleY * height) + 'px',

I found this earlier on the site:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

So, how does a relative newbie like me make all this stuff work together?

A: 
$(document).ready(function() {
$('.story-small img').each(function() {
    var maxWidth = 100; // Max width for the image
    var maxHeight = 100;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
});

});

Adam