Resize image in a square while keeping the original PHP image aspect ratio

Asked

Viewed 362 times

1

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

Currently I use a code that takes the image and resizes to 200x200, but images with different height and width obviously look 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 in this square the image of the product, respecting its proportion but making it whole fit in the white square, will it be possible?

1 answer

0


Browser other questions tagged

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