【问题标题】:Cropping image only if aspect ratio difference is small仅在纵横比差异较小时裁剪图像
【发布时间】:2020-07-30 21:19:33
【问题描述】:

我想做的是创建一个缩略图。嗯,到目前为止没有问题。我正在使用 WideImage 库。

挑战在于裁剪图像,当他的纵横比与需要制作的缩略图的纵横比仅略有不同时。 如果纵横比差异太大,图像会嵌入颜色并缩小到最终分辨率。这行得通。

如果宽高比只有一点点差异,我不想嵌入图像,因此可以在不丢失太多信息的情况下进行裁剪。

我想出的解决方案会创建一个差异值 ($diff),如果原始图像的分辨率为 400x1000,则该差异值会失败。

也许需要考虑像素纵横比?

// $values contains thumbnail resolution

// calculate proportional dest width if needed
if (!isset($values['w'])) {
    $values['w'] = round($values['h'] * ($orig_width / $orig_height));
}
// calculate proportional dest height if needed
if (!isset($values['h'])) {
    $values['h'] = round($values['w'] * ($orig_height / $orig_width));
}

// this is what it is about
$orig_diff = (abs($orig_width - $orig_height) * 100) / max(array($orig_width, $orig_height));
$thumb_diff = (abs($values['w'] - $values['h']) * 100) / max(array($values['w'], $values['h']));
$diff = abs($orig_diff - $thumb_diff);

// crop if ratio difference is small
if ($diff < 10) {
    $image = $image->resize($values['w'], $values['h'], 'outside', 'any');
    $image = $image->crop("center", "middle", $values['w'], $values['h']);
} else {
    // resize 
    if ($orig_width > $orig_height) {
        $image = $image->resize($values['w'], $values['h'], 'inside', 'down');
    } else {
        $image = $image->resize(null, $values['h'], 'inside', 'down');
    }
}

// embed if nessesary ( this is working and can be ignored)
if ($image->getWidth() < $values['w'] || $image->getHeight() < $values['h']) {
    $rgb = array();
    $resize_color = 'FFFFFF';

    for ($x = 0; $x < 3; $x++) {
        $rgb[$x] = hexdec(substr($resize_color, (2 * $x), 2));
    }
    $white = $image->allocateColor($rgb[0], $rgb[1], $rgb[2]);
    $image = $image->resizeCanvas($values['w'], $values['h'], 'center', 'middle', $white);
}

【问题讨论】:

    标签: php image-processing crop wideimage


    【解决方案1】:

    我通过简化找到了一个可行的解决方案:

    $orig_ratio = $orig_width / $orig_height;
    $thumb_ratio = $values['w'] / $values['h'];
    
    $diff = abs($orig_ratio - $thumb_ratio);
    
    // crop if ratio differenz small
    if ($diff < 0.26) {
        $image = $image->resize($values['w'], $values['h'], 'outside', 'any');
        $image = $image->crop("center", "middle", $values['w'], $values['h']);
    } else {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2020-12-13
      相关资源
      最近更新 更多