Resize image with PHP while maintaining proportion

7

I'd like to resize images by proportion from a remote link using PHP. Is this possible?

Type:

  

link

for

  

link

Note: In this case, the 2 addresses belong to me. No image theft.

    
asked by anonymous 19.03.2014 / 02:47

2 answers

9

Solution with the GD library

A very common thing in standard PHP installations is the GD library to be integrated into the distribution. If this is your case, simply use the imagecopyresampled() function to generate an image with new size.

bool imagecopyresampled ( resource $img_destino, resource $img_origem,
                            int $x_destino , int $y_destino,
                            int $x_origem, int $y_origem,
                            int $largura_destino, int $altura_destino,
                            int $largura_origem, int $altura_origem )

Example usage, coming from php page linked, but adapted to the question:

<?php
   // O arquivo. Dependendo da configuração do PHP pode ser uma URL.
   $filename = 'original.jpg';
   //$filename = 'http://exemplo.com/original.jpg';

   // Largura e altura máximos (máximo, pois como é proporcional, o resultado varia)
   // No caso da pergunta, basta usar $_GET['width'] e $_GET['height'], ou só
   // $_GET['width'] e adaptar a fórmula de proporção abaixo.
   $width = 200;
   $height = 200;

   // Obtendo o tamanho original
   list($width_orig, $height_orig) = getimagesize($filename);

   // Calculando a proporção
   $ratio_orig = $width_orig/$height_orig;

   if ($width/$height > $ratio_orig) {
      $width = $height*$ratio_orig;
   } else {
      $height = $width/$ratio_orig;
   }

   // O resize propriamente dito. Na verdade, estamos gerando uma nova imagem.
   $image_p = imagecreatetruecolor($width, $height);
   $image = imagecreatefromjpeg($filename);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

   // Gerando a imagem de saída para ver no browser, qualidade 75%:
   header('Content-Type: image/jpeg');
   imagejpeg($image_p, null, 75);

   // Ou, se preferir, Salvando a imagem em arquivo:
   imagejpeg($image_p, 'nova.jpg', 75);
?>
  

Note that in the example we are opening the image of a file, but the function also serves to open a URL, just changing the path provided. See the directive directive allow_url_fopen of PHP, which controls this behavior.


If you prefer to crop the image

The above code causes the image to fit to the specified extent, leaving "leftover" on the smaller side. If you prefer to occupy the total area, simply change it with the following section:

// inverte a comparação e calcula o offset
if ($width/$height < $ratio_orig) { 
   $dif_w = $height*$ratio_orig/2-$height;
   $dif_h = 0;
} else {
   $dif_w = 0;
   $dif_h = $width/$ratio_orig/2-$width;
}

$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
// e ajusta a origem
imagecopyresampled($image_p, $image, -$dif_w, -$dif_h, 0, 0, $width, $height, $width_orig, $height_orig);
    
19.03.2014 / 03:53
3

You can use WideImage to resize the image.

For example:

$path = $_GET['img'];

// faça as verificações de validade da imagem...

$image = WideImage::load($path);

// scala:
$width = $_GET['width']; // verifique se é válido.

if($width > 0)
{
    $scale = $image->getWidth()/$width;
}
else
{
    //tratar caso de largura inválida.
}

// Calcula a altura equivalente a largura passada.
$height = $image->getHeight() * $scale;

$resizedImage = $image->resize($width, $height);

// Daqui para frente você faz o que deve fazer com sua imagem.
// Por exemplo:
$resizedImage->saveToFile('imagem_redimencionada.jpg');
// Ou:
header("Content-type: image/jpeg");
$resizedImage->output('jpg', 100); // Onde 100 é a qualidade em %
    
19.03.2014 / 03:04