. . .

How to write text on existing image using php

Published: July 1, 2013

On This Page

    The post below describes an easy and quick way to write text over an existing image using PHP. You can use this method to watermark your images and can put it to use in number of other ways.

     

    First we would have to make the existing image editable to write text on that image. For that we have option of using three different php functions depending upon the type of image we are using. These functions are:

     

     

     

     

    imagecreatefromgif()
    imagecreatefromjpeg()
    imagecreatefrompng()

     

    In this case we would be using a .png type image.

     

     

    Next you need a function that would actually write text on top of existing image. For that we would be using the imagettftext() function.

     

     

     

     

    imagettftext ( $image , $size , $angle , $x ,  $y , $color ,$fontfile , $text )

     

    Here is what you have to do :

     

     

    First we have to set a content type, for that you would have to include the following line :

     

     

    header('Content-Type: image/png');

     

     

    Now create an image on top of which you would be adding your text using PHP

     

     

    $im = imagecreatefrompng("/path/to/image/image.png");
    // if there's an error, stop processing the page:
    if(!$im)
    {
    die("");
    }

     

    Next we we would create some colors to be used on image:

     

     

     

     

    $white = imagecolorallocate($im, 255, 255, 255);
    $black = imagecolorallocate($im, 0, 0, 0);

     

    Now you have the image ready, all you have to do is add text to your image.

     

     

     

     

    $text = 'Discretelogix...';
    // Replace path by your own font path
    $font = '/path/to/font/arial.ttf';

     

    You can also add  some shadow to the text

     

     

    imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

     

    Add the text

     

     

    imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

     

    Using imagepng() results in clearer text compared with imagejpeg()

     

     

    imagepng($im);
    imagedestroy($im);
    ?>
     

     

    Don't forget to share this post

      Let's Build Digital Excellence Together


      • Cost Efficient Solutions.
      • Minimal Timelines.
      • Effective Communication.
      • High Quality Standards.
      • Lifetime Support.
      • Transparent Execution.
      • 24/7 Availability.
      • Scalable Teams.

      Join Our 200+ Happy Clients Across Globe


      Free Consultation.

        Do you need tech help of your startup/business? Experts from our team will get in touch with you.

        Please do not post jobs/internships inquiries here.