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

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

问题描述

我正在尝试编写一个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天全站免登陆