Resize image in a square while maintaining proportion of the original PHP image

1

What happens is this: I'm pulling some product photos from an XML link, and the images come in different sizes.

I currently use a code that takes the image and resizes it to 200x200, but images with different height and width obviously make it strange.

$img_path     = (string) $googleBase->image_link;

$destination  = $img_server_folder_path;

$stlName = "stl";

$dimensions = getimagesize($img_path);

$w = $dimensions[0];
$h = $dimensions[1];

$ratios = [
    'small' => 200/$w
];

$resource = imagecreatefromstring( file_get_contents( $img_path ) );

foreach ( $ratios as $name => $ratio ) {

$w2 = $w * $ratio;
$h2 = round($h * $ratio);

$output = imagecreatetruecolor($w2, $h2);

if ( ! file_exists( $img_server_folder_path . $row['NomeLoja'] ) ) {
    mkdir( $img_server_folder_path .    $row['NomeLoja'], 0777, true );
}

// definimoso caminho no servidor para salvar a imagem | evita erro de acesso a pasta
$imagem = $img_server_folder_path . $row['NomeLoja'] . "/" . $googleBase->id . "_" . $stlName . ".jpg";

imagecopyresampled($output, $resource, 0, 0, 0, 0, $w2, $h2, $w, $h);

imagejpeg($output, $imagem, 100);

imagedestroy($output);

What I need to do is create a white square, with 200x200, and then put the image of the product in that square, respecting its proportion but making it whole fit on the white square, is it possible?

    
asked by anonymous 20.01.2017 / 18:15

1 answer

0

I was able to solve the problem using the php zebra_image library. In the library there is method that does just what it needed in a spectacular way.

link

    
06.02.2017 / 14:28