最优雅的图像到图像帧比较算法

时间:2012-02-16 01:12:06

标签: javascript

我有兴趣为这个问题寻找最优雅,最正确的解决方案。我是JS / PHP的新手,我很高兴能够使用它。目标是将给定图像的大小与图像的“帧”大小(最终成为<div><li>)进行比较,并相应地调整图像大小。用户将上传许多尺寸和形状的图像,并且将有许多尺寸和形状的框架。目标是确保任何给定的图像都能正确调整大小以适合任何给定的帧。最终的实现将在PHP中,但我正在研究JS中的逻辑。这就是我所拥有的:

//predefined variables generated dynamically from other parts of script, these are example values showing the 'landscape in landscape' ratio issue
var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300;         
//check image orientation
if ( $imageHeight == $imageWidth ) {
    var $imageType = 1; // square image
} else if ( $imageHeight > $imageWidth ) {
    var $imageType = 2; // portrait image
} else {
    var $imageType = 3; // landscape image
};
//check frame orientation and compare to image orientation
if ( $height == $width) { //square frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) {
        $deferToHeight = true;
    } else {
        $deferToHeight = false;
    };
} else if  ( $height > $width ) { //portrait frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) )  {
        $deferToHeight = true;
    } else {
        if (($imageHeight / $height) < 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
} else { //landscape frame
    if ( ( $imageType === 1 ) || ( $imageType === 2 ) ) {
        $deferToHeight = false;
    } else {
        if (($imageWidth / $width) > 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
};
//set values to match (null value scales proportionately)
if ($deferToHeight == true) { //defer image size to height of frame
    $imageWidth = null;
    $imageHeight = $height;
} else { //defer image size to width of frame
    $imageWidth = $width;
    $imageHeight = null;
};

我用一堆不同的值对它进行了测试,正常工作,但我怀疑自己可以实现更优雅的解决方案。我能做得更好吗?

2 个答案:

答案 0 :(得分:0)

以下是我最近在JS实现中处理这个确切问题的方法:

// determine aspect ratios
var a1 = imageWidth / imageHeight,
    a2 = frameWidth / frameHeight,
    widthDetermined = a1 > a2;

// set scale
var scale = widthDetermined ?
    // scale determined by width
    frameWidth / imageWidth :
    // scale determined by height
    frameHeight / imageHeight;

// set size (both dimensions) based on scale
imageWidth = scale * imageWidth;
imageHeight = scale * imageHeight;

比您的版本少得多的代码。请注意,方形大小写是以任一方式处理的,在您的版本中也可能是这样。

答案 1 :(得分:0)

如果图像是假想方形图像并且您想将其转换为肖像,那么您认为图像看起来不像是拉长了吗?我觉得比例会改变,图像可能看起来很糟糕。你怎么看?