4

I want to dynamically render text to an image with a custom font, preferably with the option to output directly or save to a file. And to automatically set the image size according to the font/size combination.

I can already do this with GD, but it doesn't handle fonts where characters overlay each other.

So now I'm looking to ImageMagick. I've found an example in the docs that seem to do what I want. Is this possible with php_magick? Especially the part where no image size is defined :) If it is not, can I make command-line magick output the raw image, so I can pass it directly to the client with PHP?

Thanks!


The real question probably is: How do I convert the IM command below to PHP code using php_magick?

convert -background lightblue -fill blue -font Arial -pointsize 72 label:Anthony
1
  • Found out how to make im return the raw image data: convert [..] png:- Commented May 16, 2011 at 19:12

2 Answers 2

16

You should be able to use the annotateImage function of the Imagick class to duplicate that functionality.

Here's a straight up copy-paste from that documentation:

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0, 
    'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, but doesn't that set the image size to 800x75? I need the size to be automatically adjusted to the font size
How can I use custom ttf font?
3

Decided to skip the API and use the command-line interface instead.

convert -background lightblue -fill blue -font Arial -pointsize 72 label:Anthony png:-

This returns the raw PNG data, which we can then output to the browser. Replace png:- with the filename to save to a file instead.

Don't forget to use escapeshellarg if you are using user input as parameters here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.