按区域调整图像大小 [英] resize image by area

查看:23
本文介绍了按区域调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 javascript 函数来根据给定区域(或在我的情况下(有些不准确)平均尺寸")调整图像大小,因为这更容易考虑.而不是输入最大高度和宽度, 我想在最大区域内输入,以便长或窄的图像在视觉上看起来大致相同.

I am trying to write a javascript function to resize an image based on a given area (or in my case (somewhat inaccurate) 'average dimension' since that's easier to think in terms of. Rather than feeding in maximum height and width, I want to feed in maximum area so that long or narrow images will appear visually to be roughly the same size.

不过,我真的被它的数学方面吸引住了......只是如何逻辑它,因为我最近没有做太多数学.

I'm getting really caught on the math aspect of it, though... just how to logic it, as I haven't done much math of late.

基本上,给定一个纵横比,我想确定一个区域内的最大尺寸.

Basically, given an aspect ratio I want to determine the maximum size within an area.

像这样:

function resizeImgByArea(img, avgDimension){
    var w = $(img).width();
    var h = $(img).height();
    var ratio = w/h;
    var area = avgDimension * avgDimension;
    var targetHeight //something involving ratio and area
    var targetWidth //something involving ratio and area
    $(img).width(targetWidth);
    $(img).height(targetHeight);
}

不确定这是否是这里的主题,但我想不通.

Not sure if this is on topic here, but I'm not able to brain it.

推荐答案

这是我想出的函数,它比上面提到的更简单,并且可以满足我的需要.由于我使用的特殊要求,它限制为一个设置的 maxWidth,但不限制高度.. 抛出 maxHeight 以及一些清理可能是合适的,但它完成了.

Here is the function I came up with that's simpler than some mentioned and does what I need. It constrains to a set maxWidth, but not height because of the particular requirements I was using.. it would probly be appropriate to throw on a maxHeight as well as well as some cleanup, but it gets 'er done.

function resizeImgByArea(imgId, avgDimension){
   var node, w, h, oldArea, oldAvgDimension, multiplicator, targetHeight, targetWidth, defAvgDimension;
   node = $('#' + imgId);
   node.css('width', '').css('height', '');
   var maxW = $('#' + imgId).css('maxWidth');
   if (maxW){
       defAvgDimension = maxW;
   } else {
       defAvgDimension = 200;
   }
   avgDimension = (typeof avgDimension == "undefined")?'defAvgDimension':avgDimension;
   w = node.width();
   h = node.height();
   oldArea = w*h;
   oldAvgDimension = Math.sqrt(oldArea);
   if (oldAvgDimension > avgDimension){
       multiplicator = avgDimension / oldAvgDimension;
       targetHeight = h * multiplicator;
       targetWidth = w * multiplicator;
       node.width(targetWidth);
       node.height(targetHeight);
   }
}

这篇关于按区域调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆