我需要一种算法来确定图像可能的最大比例增加。
规则(Flash Player的BitmapData对象的大小限制,但这不是Flash问题):
因此,如文档中所述:
如果BitmapData对象是8,191像素 宽,它只能是2,048像素 高。
在我的代码中,我首先确定是否有任何这些规则被破坏,如果它们是抛出则抛出错误。这让我知道任何加载并且不会抛出错误的图像都具有可伸缩性。
我正在使用的图片是2514 width x 1029 height
。此图像不会抛出错误,因为宽度和高度均小于8,191,并且它的像素数或宽度乘以高度小于16,777,215。
我认为自己是正确的,并且对我的数学技能没有多少信心,但以下是我想出的确定图像最大允许比例的方法。
private static const MAX_BITMAP_MEASUREMENT:uint = 8191;
private static const MAX_BITMAP_PIXELS:uint = 16777215;
var imageWidth:uint = 2514;
var imageHeight:uint = 1029;
var roughScaleUp:Number = 1.0 / Math.max(imageWidth, imageHeight) * MAX_BITMAP_MEASUREMENT;
var scaleBack:Number = Math.max(Math.min(imageWidth, imageHeight) * roughScaleUp - MAX_BITMAP_PIXELS / MAX_BITMAP_MEASUREMENT, 0);
var maxScale:Number = 1.0 / (Math.max(imageWidth, imageHeight) + scaleBack) * MAX_BITMAP_MEASUREMENT;
此代码输出我的图像的最大比例为2.145144435977516,但我测试了它并且仍然有很多像素空间,所以它应该能够扩展得更多并且我很确定我的代码非常糟糕错。
这里的任何数学巫师都在关心帮助一个卑微的艺术学校毕业生?我已经完全准备好接受这个问题可能有一个更简单的解决方案,我已经准备好接受绑定了。
答案 0 :(得分:2)
您必须将宽度和高度乘以常数,并且乘法的缩放结果应小于16777215.
所以
a^2 * w * h == 16,777,215
对于w
和h
a = 2.5466520486244177 [= Sqrt(16,777,215 / (w*h)) ]
因此,对于新w
和h
的值,您会得到:
NewW = a * w = 6402.283250241786
NewH = a * h = 2620.5049580345258
......将它们围绕下来:)
答案 1 :(得分:0)
嗯,这是一个丑陋的解决方案。我无法完成四舍五入,所以我粗暴地强调了4种可能性以获得最佳值。代码应该直截了当地理解:
from math import *
def opt_image(w, h):
aspect = w / h
if aspect >= 1:
v = min(sqrt(1677215 / aspect), 8191)
a, b = floor(aspect * v), floor(v)
area, nw, nh = max([ ( (a+x)*(b+y), (a+x), (b+y) ) for x in range(2) for y in range(2) if (a+x)*(b+y) < 1677215 ])
return nw, nh
a, b = opt_image(w, h)
return b, a
对于宽度为2514,高度为1029的示例;我得到了:
(1831.0,916.0)