How to resize image with fixed width

Asked

Viewed 1,175 times

0

I’m having trouble resizing an image to a specific width, I can only resize proportionally according to width or height.

With only:

<?php

$original_width = x;
$original_height = y;

$redimensionar = 200;

// Novos valores
$width = 0;
$height = 0;

if ($original_width > $original_height) {
    $ratio = ($redimensionar / $original_width);
}
else {
    $ratio = ($redimensionar / $original_height);
}

$width = ($original_width * $ratio);
$height = ($original_height * $ratio);

The problem with that is that the image may be 200 wide or 200 high, what I have to do and I can’t leave the width always 200 and the proportional height.

[EDITED]

When I made a code to always resize to 200 width, the ratio calculation was backwards, so I was working with just this above.

1 answer

2


If you want the image to always be 200 wide then its new width should be 200 and the new height should be proportional, or is equal to its ratio times the new width.

<?php

$original_width = x;
$original_height = y;

$redimensionar = 200;

// Novos valores
$width = 0;
$height = 0;

$ratio = ($original_height / $original_width);

$width = $redimensionar;
$height = ($width * $ratio);

This is because the reason altura/largura should remain constant (for the image to scale proportionally) so if the new width is 200 the new height is obtained by doing largura * razão which in this case is 200 * razão.

  • I was doing almost that, my code failed because I was calculating ($original_width / $original_height) when it’s the other way around

  • But if you want the width to always be 200 that’s shape. Or you want the smallest dimension to be 200?

  • It would always be 200 wide, the real problem was that my ratio calculation was backwards

  • Got it, good that you managed to solve! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.