Using GD and Freetype2, if both installed, then you can add text to a JPEG using the following steps.
create an image resource from the file using imagecreatefromjpeg()
add text to that image using the Freetype2 library, via the function imagefttext()
(note you can also use the function imagettftext()
if you only have Freetype installed and not Freetype2).
save the modified image using imagejpeg()
Example:
[I've literally just typed this in to the browser, never run it - so if it needs amendment, apologies.]
/**
* Annotate an image with text using the GD2 and Freetype2 libraries
*
* @author Orbling@StackOverflow
*
* @param string $sourceFileName Source image path
* @param string $destinationFileName Destination image path
* @param string $text Text to use for annotation
* @param string $font Font definition file path
* @param float $fontSize Point size of text
* @param array $fontColour Font colour definition, expects
array('r' => #, 'g' => #, 'b' => #),
defaults to black
* @param int $x x-coordinate of text annotation
* @param int $y y-coordinate of text annotation
* @param float $rotation Angle of rotation for text annotation,
in degrees, anticlockwise from left-to-right
* @param int $outputQuality JPEG quality for output image
*
* @return bool Success status
*/
function imageannotate($sourceFileName, $destinationFileName,
$text, $font, $fontSize, array $fontColour = NULL,
$x, $y, $rotation = 0, $outputQuality = 90) {
$image = @imagecreatefromjpeg($sourceFileName);
if ($image === false) {
return false;
}
if (is_array($fontColour) && array_key_exists('r', $fontColour)
&& array_key_exists('g', $fontColour)
&& array_key_exists('b', $fontColour)) {
$colour = imagecolorallocate($image, $fontColour['r'],
$fontColour['g'],
$fontColour['b']);
if ($colour === false) {
return false;
}
} else {
$colour = @imagecolorallocate($image, 0, 0, 0);
}
if (@imagefttext($image, $fontSize, $rotation,
$x, $y, $colour, $font, $text) === false) {
return false;
}
return @imagejpeg($image, $destinationFileName, $outputQuality);
}
NB. For debugging, I would remove the @
symbols.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…