How to merge images and text with PHP

0

Good afternoon.

I'm trying to automate a process of creating badges for an event.

I want you to fill out the information on the form (name, company, e-mail and photo), fill in the gaps in the image and make it as a single JPEG image.

ButI'vecometoapointwhereInolongerknowhowtoproceed.

I'mabeginnerinPHP.

ThiscodeIgotontheinternetandmodifiedsothatIcanachievethegoal.

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

// link to the font file no the server
$fontname = 'font/Roboto-Regular.ttf';
// controls the spacing between text

//JPG image quality 0-100
$quality = 100;

function create_image($user){
$height = 0;
$i=30;

global $fontname;	
global $quality;
global $im;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";	

// if the file already exists dont create it again just serve up the original	
//if (!file_exists($file)) {	


// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
$src = imagecreatefromjpeg('fotos/foto.jpg');

// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);

// this defines the starting height for the text block
$y = imagesy($im) - $height - 550;
$imgy = imagesy($src) - $height - 550;

imagecopymerge($im, $src, 124, 463, 0, 0, 353, 354, 100);


// loop through the array and write the text	
foreach ($user as $value){
	// center the text in our image - returns the x value
	$x = center_text($value['name'], $value['font-size']);	
	imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
	// add 32px to the line height for the next text block
	$i = $i+36;
}

// create the image
imagejpeg($im, $file, $quality);

//}

return $file;	
}

function center_text($string, $font_size){

global $fontname;

$image_width = 1004;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);

return ceil(($image_width - $dimensions[4]) / 5.0);				
}



$user = array(

array(
	'name'=> 'Nome',
	'font-size'=>'36',
	'color'=>'grey'),

array(
	'name'=> 'Cargo',
	'font-size'=>'16',
	'color'=>'grey'),

array(
	'name'=> 'Organização',
	'font-size'=>'13',
	'color'=>'green'
	)
);

if(isset($_POST['submit'])){

$error = array();

if(strlen($_POST['name'])==0){
	$error[] = 'Please enter a name';
}

if(strlen($_POST['job'])==0){
	$error[] = 'Please enter a job title';
}		

if(strlen($_POST['email'])==0){
	$error[] = 'Please enter an email address';
}

if(count($error)==0){

	$file = rand(1000,100000)."-".$_FILES['foto']['name'];
    $file_loc = $_FILES['foto']['tmp_name'];
	 $file_size = $_FILES['foto']['size'];
	 $file_type = $_FILES['foto']['type'];
	 $folder="fotos/";
 
 	move_uploaded_file($file_loc,$folder.$file);

	$user = array(

		array(
			'name'=> $_POST['name'], 
			'font-size'=>'27',
			'color'=>'grey'),
		
		array(
			'name'=> $_POST['job'],
			'font-size'=>'16',
			'color'=>'grey'),
		
		array(
			'name'=> $_POST['email'],
			'font-size'=>'13',
			'color'=>'green'
			),
		array(
			'name'=> $_POST['email'],
			'font-size'=>'13',
			'color'=>'green'
			)
		
		);	
	$im = imagecreatefromjpeg("pass.jpg");	
	imagecopymerge($im, imagecreatefromjpeg($folder.$file), 124, 463, 0, 0, 353, 354, 100);
}

}

// run the script to create the image
$filename = create_image($user);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Gerar Crachás</title>
<link href="../style.css" rel="stylesheet" type="text/css" />

<style>
input{
	border:1px solid #ccc;
	padding:8px;
	font-size:14px;
	width:300px;
}

.submit{
	width:110px;
	background-color:#FF6;
	padding:3px;
	border:1px solid #FC0;
	margin-top:20px;}	

	</style>

</head>

<body>

	<img src="<?=$filename;?>?id=<?=rand(0,1292938);?>" /><br/><br/>

	<ul>
		<?php if(isset($error)){

			foreach($error as $errors){

				echo '<li>'.$errors.'</li>';

			}


		}?>
	</ul>

	<a href="<?php echo $filename; ?>">Clique aqui para Baixar</a>

	<p>You can edit the image above by typing your details in below. It'll then generate a new image which you can right click on and save to your computer.</p>

	<div class="dynamic-form">
		<form action="" method="post" enctype="multipart/form-data">
			<label>Name</label>
			<input type="text" value="<?php if(isset($_POST['name'])){echo $_POST['name'];}?>" name="name" placeholder="Name"><br/>
			<label>Job Title</label>
			<input type="text" value="<?php if(isset($_POST['job'])){echo $_POST['job'];}?>" name="job" placeholder="Job Title"><br/>
			<label>Email</label>
			<input type="text" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>" name="email" placeholder="Email"><br/>
			<label>Add Photo</label>
			<input type="file" name="foto" placeholder="Foto"/><br>
			<input name="submit" type="submit" class="btn btn-primary" value="Update Image" />
		</form>
	</div>

</body>
</html>

Any suggestions?

    
asked by anonymous 21.11.2016 / 19:51

2 answers

1

The 1st example of this script here: Adding Text to Image with PHP . Then you can adjust font, positioning, create a PDF from the image, etc.

Using truetype font, text placement, writing to a directory, and return in the browser:

    # Header informando que é uma imagem JPEG
    header('Content-type: image/jpeg');
    # Declaração das variáveis usadas
    $imgName = strtoupper(substr(md5(date(DATE_RFC822)), 0, 20));
    $imgPath = "cache/$imgName.jpg";
    $imgQuality = 90;
    # Carregar imagem já existente no servidor
    $img = imagecreatefromjpeg("imagem.jpg");
    $font = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf";
    # Cores de saída
    $black = imagecolorallocate($img, 0, 0, 0);
    # Texto que será escrito na imagem
    $texto = urldecode("Texto inserido na imagem\n");
    $texto.= $imgName;
    # Posicionamento
    $bbox = imagettfbbox(10, 45, $font, $texto);
    $x = $bbox[0] + (imagesx($img) / 2) - ($bbox[4] / 2) - 130;
    $y = $bbox[1] + (imagesy($img) / 2) - ($bbox[5] / 2) - 40;
    # Escrever na $img
    imagettftext($img, 25, 0, $x, $y, $black, $font, $texto);
    # Envia a imagem para o arquivo
    imagejpeg($img, $imgPath, $imgQuality);
    # Mostra a imagem no navegador
    imagejpeg($img, NULL, $imgQuality);
    imagedestroy($img);
    
21.11.2016 / 21:06
0

I've already had to do something similar to generate signatures for emails from the company where I work. The solution I found was to position the elements with css and use a library that takes a screenshot of the html elements, there I hid the originals and it just showed the screenshot taken. Take a look at the library , or at my project , maybe it will help you.

    
21.11.2016 / 21:37