Place an image in the center of another image in PHP

Asked

Viewed 2,091 times

2

I have an image . png of for example 200x200px.

I need her to stay with 300x300px, but without enlarging the image, just by putting it inside and centering on a 300x300px white square.

Is that possible? How can I center this image?

Remembering that I need to do this on the server side, using the PHP image library.

Thank you.

3 answers

3


I believe that you are trying to do this through form to send the image, so I worked out an answer thinking about it.

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="img" />
    <input type="submit" name="ok" value="Enviar" />
</form>

<?php

$tempname = $_FILES["img"]["tmp_name"]; // Caminho completo da imagem original.
$extension = strtolower(pathinfo($_FILES["img"]["name"], PATHINFO_EXTENSION)); // Extraindo extensão com 'pathinfo' da imagem original.
$name = "new_img"; // Nome do novo arquivo de imagem
$url = "images/".$name.".".$extension; // Caminho onde será salvo a nova imagem
$max_width = 300; // Largura final da imagem
$max_height = 300; // Altura final da imagem

$allowed_extensions = array('gif', 'jpg', 'png'); // Extensões permitidas

if(in_array($extension, $allowed_extensions)) { // Se extensão é permitida...
    move_uploaded_file($tempname, $url); // Move para o caminho definido em '$url'
} else return "Arquivo não permitido.";

// Pega a largura, altura, tipo e atributo da imagem
list($image_width, $image_height, $type, $attribute) = getimagesize($url);

// Calcula o coeficiente para centralização
$x = round(($max_width - $image_width) / 2);
$y = round(($max_height - $image_height) / 2);                                            

// Cria uma nova imagem com o novo tamanho
$new_image = imagecreatetruecolor($max_width, $max_height);

// Define o background desta nova imagem (RGB), neste caso, 'branco' como precisa.
$bg = imagecolorallocate($new_image, 255, 255, 255);
imagefill($new_image, 0, 0, $bg);

switch ($type){
    case 1: // Se a imagem for GIF...
        $source = imagecreatefromgif($url); // Pega a imagem original GIF
        imagecopyresampled($new_image, $source, $x, $y, 0, 0, $image_width, $image_height, $image_width, $image_height); 
        imagegif($new_image, $url); // Gera a nova imagem sobrescrevendo a original
        break;
    case 2: // Se a imagem for JPG...
        $source = imagecreatefromjpeg($url); // Pega a imagem original JPG
        imagecopyresampled($new_image, $source, $x, $y, 0, 0, $image_width, $image_height, $image_width, $image_height);
        imagejpeg($new_image, $url, 70); // Gera a nova imagem sobrescrevendo a original (com resolução de 70 (vai de 0 à 100))
        break;
    case 3: // Se a imagem for PNG...
        $source = imagecreatefrompng($url); // Pega a imagem original PNG
        imagecopyresampled($new_image, $source, $x, $y, 0, 0, $image_width, $image_height, $image_width, $image_height);
        imagepng($new_image, $url, 9); // Gera a nova imagem sobrescrevendo a original (com compactação de 9 (vai de 0 à 9))
        break;
}

// Destrói as imagens criadas
imagedestroy($new_image);
imagedestroy($source);

I just didn’t comment on the function imagecopyresampled(), found it best to post this suggested reading:

http://php.net/manual/en/function.imagecopyresampled.php

  • Thank you very much. Actually it was not through a form but solved the same way. I knew these other functions, what I needed was this round function. Thank you again.

  • 1

    [edited] A tip Thyago and @Juniorzancan this method of checking extension is not safe, I recommend reading: http://answall.com/a/73497/3635

  • Thanks @Guilhermenascimento, but the script I’m using already checks the extension and not just by name. So from that script I just used the "round part".

  • @Guilhermenascimento, thank you very much for the tip, was not aware, by the visa I risk even receiving an executable only with the extension edited for png! =)

2

You can use imagecopymerge for this, as described in the documentation:

bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x ,
                        int $dst_y , int $src_x , int $src_y , int $src_w ,
                           int $src_h , int $pct )

See an example, read the comments inside the code:

<?php
$dest       = imagecreatefromjpeg('foto.jpg'); //Pega a imagem principal
$marcadagua = imagecreatefromgif('marcadagua.gif'); //Pega a imagem que vai ser centralizada

//pega o tamanho da imagem principal
$dwidth  = imagesx($dest);
$dheight = imagesy($dest);

//pega o tamanho da imagem que vai ser centralizada
$mwidth  = imagesx($marcadagua);
$mheight = imagesy($marcadagua);

//Calcula a x e y posição pra colocar a imagem no centro da outra
//A função round arredonda os valores
$xPos = round(($dwidth  - $mwidth)  / 2);
$yPos = round(($dheight - $mheight) / 2);

imagecopymerge($dest, $marcadagua, $xPos, $yPos, 0, 0, $mwidth, $mheight, 100);

header('Content-Type: image/jpeg');
imagejpeg($dest);

//destrói resources 
imagedestroy($dest);
imagedestroy($marcadagua);

You can change the last argument to make the image less opaque, or be a little transparent, for example, if you do this the centered image will get a little erased:

imagecopymerge($dest, $marcadagua, $xPos, $yPos, 0, 0, $mwidth, $mheight, 70);

0

The easiest way is to superimpose an image on the other, create a 300x300 white image to serve as a base, I really like using the library Wideimage, is light and without many complications, follows the example:

<?php
    require_once('lib/WideImage.php');
    $base = WideImage::load('white.jpg'); // carregue sua base
    $imagem = WideImage::load('imagem.jpg'); // carregue sua imagem

    $base->merge($imagem, 50, 50, 100)->saveToFile('resultado.jpg'); // faça o merge

?>

o Example is very intuitive, for more information access to the site and documentation.

I hope it helps, hugs.

  • But in this case the original image would have to be 200x200px, it could not be of a dynamic size, correct?

Browser other questions tagged

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