-1

What I'm trying to do is creating a thumbnail. Well no problem so far. I'm using the WideImage Library.

The challenge is cropping the image, when his aspect ratio only differs a little from the aspect ratio of the thumbnail that needs to be made. If the aspect ratio differs too much the image gets embedded in a color and scaled down to the final resolution. That works.

I don't want to embed images if the aspect ratio only differs a little, so cropping can be done without loosing too much information.

The solution I came up with creates a difference value ($diff) that seams to fail if the original image has resolutions like 400x1000.

Maybe the pixel aspect ratio need to be considered?

// $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);
}
Mike
  • 5,416
  • 4
  • 40
  • 73

1 Answers1

0

I found a working solution by making it simple:

$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 {
    // ...
}
Mike
  • 5,416
  • 4
  • 40
  • 73