claviska / SimpleImage

A PHP class that makes working with images and GD as simple as possible.
MIT License
1.38k stars 382 forks source link

Can not add a text on image #297

Closed AsMoz3374 closed 2 years ago

AsMoz3374 commented 2 years ago

I tried to add a text on image like the following way but it didn't help me. What I am doing wrong and how do I add a text on image ? Thanks in advance

try {
  // Create a new SimpleImage object
  $image = new \claviska\SimpleImage();

  $image
    ->fromFile('background.png')                     // load image.jpg
    ->autoOrient()                              // adjust orientation based on exif data
    ->resize(500, 500)                          // resize to 320x200 pixels
    ->flip('x')                                 // flip horizontally
    ->colorize('DarkBlue')                      // tint dark blue
    //->border('black', 10)                       // add a 10 pixel black border

    ->overlay('img.jpg', 'center')  // add a watermark image
    ->toFile('new-image.png', 'image/png')
    ->text('text here', 'font.ttf', 32, '#FFFFFF', 'top', 0, 20)      
    // convert to PNG and save a copy to new-image.png
    ->toScreen();                               // output to the screen

} catch(Exception $err) {
  // Handle errors
  echo $err->getMessage();
}
AsMoz3374 commented 2 years ago

I'm leaving this answer for help in case anyone has failed to add text on the image. If you guys have a better answer please share it to help people.

try {
    // Create a new SimpleImage object
    $image = new \claviska\SimpleImage();

    $image
      ->fromFile('image.jpg')                     // load image.jpg
      ->autoOrient()                              // adjust orientation based on exif data   
      ->text('Text Here', array(
        'fontFile' => dirname(realpath(__FILE__)).'/YourFont.ttf',
        'size' => 32, // Font Size
        'anchor' => 'bottom right') // Text Position
        )  
      ->toFile('new-image.png', 'image/png') // convert to PNG and save a copy to new-image.png
      ;
  } catch(Exception $err) {
    // Handle errors
    echo $err->getMessage();
  }
claviska commented 2 years ago

Yep, you'll need to pass a TTF or OTF font through to text() as you've discovered. This is a GD thing, since it doesn't come with fonts built in.

Closing since you've discovered the solution.