Skip to content

Instantly share code, notes, and snippets.

@ghacosta
Created February 3, 2016 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghacosta/fdf38b3931b19fe094b8 to your computer and use it in GitHub Desktop.
Save ghacosta/fdf38b3931b19fe094b8 to your computer and use it in GitHub Desktop.
PHP GD: Create a blank background, resize other image and merge it with the background
<?php
// could be useful http://stackoverflow.com/questions/16774521/scale-image-using-php-and-maintaining-aspect-ratio
// El archivo
$nombre_archivo = 'inverco-sa';
$mime_type = '.png';
// Create a 210x210 image
$im = imagecreatetruecolor(210, 210);
$white = imagecolorallocate($im, 255, 255, 255);
// Draw a white rectangle
imagefilledrectangle($im, 0, 0, 210, 210, $white);
// Save the image
imagepng($im, './imagefilledrectangle.png');
imagedestroy($im);
// Obtener dimensiones del logo
list($ancho, $alto) = getimagesize($nombre_archivo.$mime_type);
$nuevo_ancho = 210;
$nuevo_alto = ($nuevo_ancho * $alto) / $ancho;
// Redimensionar
$imagen_p = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);
$imagen = imagecreatefrompng($nombre_archivo.$mime_type);
imagecopyresampled($imagen_p, $imagen, 0, 0, 0, 0, $nuevo_ancho, $nuevo_alto, $ancho, $alto);
// Imprimir
imagepng($imagen_p, './'.$nombre_archivo.'-resized'.$mime_type);
imagedestroy($imagen_p);
imagedestroy($imagen);
$dest = imagecreatefrompng('imagefilledrectangle.png');
$src = imagecreatefrompng($nombre_archivo.'-resized'.$mime_type);
imagealphablending($dest, false);
imagesavealpha($dest, true);
//dst_im src_im dst_x dst_y src_x src_y src_w src_h pct (always 100)
$dst_y = (210 / 2) - ($nuevo_alto / 2);
imagecopymerge($dest, $src, 0, $dst_y, 0, 0, 210, $nuevo_alto, 100); //have to play with these numbers for it to work for you, etc.
imagepng($dest, $nombre_archivo.'-square'.$mime_type);
imagedestroy($dest);
imagedestroy($src);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment