-1

我想要做的是创建一个缩略图。嗯,到目前为止没有问题。我正在使用 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);
}
4

1 回答 1

0

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

$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 {
    // ...
}
于 2020-04-17T20:26:25.083 回答