How to merge images and text with PHP

Asked

Viewed 932 times

0

Good afternoon.

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

I want when the user fills in the form information (name, company, email and photo), the filled information complete the image gaps and make everything as a single JPEG image.

inserir a descrição da imagem aqui

But I’ve reached a point I no longer know but how to proceed.

I’m a beginner in PHP.

This code I took on the Internet and modified so that I can achieve the goal.

<?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?

2 answers

1


The first example of this script here: Adding Text to the Image with PHP. After vc can adjust source, positioning, create a PDF from the image, etc.

Using truetype font, text placement, write to a directory and return to 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);
  • Well, it was exactly what I needed. But it’s a bit incomplete. I’d like to know how I can embed the image upload into this code. After handling the upload and moving to the directory, I have difficulty using the method "imagecopymerge()" with the file in which it was uploaded, it gives error in the second parameter that is responsible for the directory path.

  • I didn’t really understand what you want, but I edited the answer adding some features. Now the code saves the image (imagejpeg($img, $imgPath, $imgQuality); in the directory $imgPath before returning the buffer pro browser. Remember to give the correct permissions for the server to write to $imgPath.

  • That’s exactly what it was. Thank you very much .

0

I’ve had to do something similar to generate email signatures for the company I work for. The solution I found was to position the elements with css and use a library that takes a screenshot of the html elements, then I hid the originals and showed only the screenshot taken. Take a look at the library, or in the my project, maybe it’ll help you.

  • I really liked your project, congratulations! In my case I will give preference for a code "clean" because I need to reuse some native PHP functions, but I will definitely take some ideas from your project.

Browser other questions tagged

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