用文本覆盖图像并转换为图像

Den*_*one 4 php text gd

我想在jpg中添加文本来创建新图像.

服务器上已经有了image_1.jpg,我想把用户提交的副本放在image_1.jpg的顶部,创建一个新的图像,将副本和原始图像组合成一个新的光栅化jpg

我知道你可以使用GD Librariesphp栅格化的副本,但可分层吗?我的网站是用PHP编写的,但我愿意使用第三方插件.

答案:(旧帖子)但我需要什么http://blog.rafaeldohms.com.br/2008/02/12/adding-text-to-images-in-real-time-with-php/

Orb*_*ing 6

使用GD和Freetype2(如果已安装),则可以使用以下步骤将文本添加到JPEG.

  1. 使用从文件创建图像资源 imagecreatefromjpeg()

  2. 使用Freetype2库通过该函数向该图像添加文本imagefttext()(注意,imagettftext()如果只安装了Freetype而不是Freetype2,也可以使用该函数).

  3. 使用保存修改后的图像 imagejpeg()

例:

[我实际上只是将它输入浏览器,从不运行它 - 所以如果它需要修改,请道歉.]

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

NB.为了调试,我会删除@符号.