Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text to an image with PHP GD library

Tags:

html

php

image

gd

I have image creation code in image_creator.

<?php
header("Content-Type: image/jpeg");
$im = ImageCreateFromGif("photo.gif"); 
$black = ImageColorAllocate($im, 255, 255, 255);
$start_x = 10;
$start_y = 20;
Imagettftext($im, 12, 0, $start_x, $start_y, $black, 'verdana.ttf', "text to write");
Imagejpeg($im, '', 100);
ImageDestroy($im);
?> 

The file for image output is image.php and has below code

<html>
<head>
</head>
<body>
    <img src="http://localhost/image_creator.php"/> 
</body>

</html>

When I run image.php, I just get a blank page. Why is it so?

like image 480
roy mathew Avatar asked Nov 07 '12 10:11

roy mathew


People also ask

How do I put text over a picture in laravel?

if you are use laravel and you want to add text on image or resize, crop image then we can do with "intervention/image" pakacke.

Can we draw images using PHP library?

First, you can draw (make images) with PHP. Second, only a sadist would try to replace a Photoshop-like tool with any programming interface to a drawing tool. Third, the GD image library for drawing in PHP has many drawbacks. Those drawbacks are pretty significant, though some of them are certainly a matter of opinion.

What does PHP GD do?

GD is an open source code library for the dynamic creation of images. GD is used for creating PNG, JPEG and GIF images and is commonly used to generate charts, graphics, thumbnails on the fly.


2 Answers

Use this to add text to image (copied from PHP for Kids)

<?php
//Set the Content Type
header('Content-type: image/jpeg');

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('sunset.jpg');

// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 255, 255, 255);

// Set Path to Font File
$font_path = 'font.TTF';

// Set Text to Be Printed On Image
$text = "This is a sunset!";

// Print Text On Image
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

// Send Image to Browser
imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image);
?>
like image 171
Akhilraj N S Avatar answered Oct 12 '22 23:10

Akhilraj N S


Problem here is, $black = ImageColorAllocate($im, 255, 255, 255); //<== this not black, its white //for black it should be like,

$black = ImageColorAllocate($im, 0, 0, 0);
like image 35
Ali Nawaz Hiraj Avatar answered Oct 13 '22 01:10

Ali Nawaz Hiraj