Answer the question
In order to leave comments, you need to log in
Wrong aspect ratio calculation?
Script to bring all images to the same aspect ratio without stretching (overlaying on a white background)
But, for some reason, in fact, there is an error of several pixels in the aspect ratio. How to fix it?
<?php
$fnamefoto = $_GET['name'];
$img = new Imagick();
$img->readImage('/var/www/localhost/files/images/'.$fnamefoto);
$img->setImageFormat('jpeg');
$val = $img->getImageWidth() / $img->getImageHeight();
if ($val > 1.77272727273) {
$height = intval($img->getImageHeight() + ($img->getImageHeight() * ($val - 1.77272727273)));
$width = $img->getImageWidth();
} else {
$width = intval($img->getImageWidth() + ($img->getImageWidth() * (1.77272727273 - $val)));
$height = $img->getImageHeight();
}
$canvas = new Imagick();
$canvas->newImage($width, $height, 'white', 'jpg');
$geometry = $img->getImageGeometry();
$x = ($width - $geometry['width']) / 2;
$y = ($height - $geometry['height']) / 2;
$canvas->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y);
$canvas->writeImage('/var/www/localhost/files/images/'.$fnamefoto);
Answer the question
In order to leave comments, you need to log in
Somehow you have too difficult to calculate everything.
$width = $img->getImageWidth();
$height = $img->getImageHeight();
if ($height*16 > $width*9) {
$width = $height*16/9;
} else {
$height = $width*9/16;
}
You do floating point calculations exactly, but then round up to an integer, and so on twice. Here is the difference.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question