开发者

how do I find the h&w of an image and convert to vars, then use those vars

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?


$(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
    }
});

});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜