doufu7464 2014-05-27 22:50
浏览 13

使用GD库中心2行文本

I'm adding a lon string of text onto an image using PHP GD library.

The string may be 2 lines long, or 3.

The problem is that it's taking the with of the string with a linebreak in it, and then centering that, but its not centering line two.

It creates images like this:

enter image description here

When I want it to be centered for both lines.

Here's the code I have:

header('Content-type: image/jpeg');

$image       = imagecreatefromjpeg($_FILES['image']['tmp_name']);
$imagewidth  = imagesx($image);
$imageheight = imagesy($image);

$black       = imagecolorallocatealpha($image, 0, 0, 0, 40);
imagefilledrectangle($image, 0, 0, $imagewidth, 207, $black);

$white       = imagecolorallocate($image, 255, 255, 255);
$text        = wordwrap($_POST['headline'], 33, "
" );

$font        = 'HelveticaWorld-Bold.ttf';
$fontsize    = 45;
$fontangle   = 0;

### Get exact dimensions of text string
$box = @imageTTFBbox($fontsize, $fontangle, $font, $text);

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth / 2) - ($textwidth / 2) - 2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2);
$ycord = 80;

function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
  for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
  for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
  $bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
  return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}

### imagettftext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $font, $text);
$stroke_color = imagecolorallocate($image, 0, 0, 0);
imagettfstroketext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $stroke_color, $font, $text, 7);

imagejpeg($image, NULL, 100);
imagedestroy($image);         
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 BP神经网络控制倒立摆
    • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
    • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
    • ¥30 Unity接入微信SDK 无法开启摄像头
    • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
    • ¥20 cad图纸,chx-3六轴码垛机器人
    • ¥15 移动摄像头专网需要解vlan
    • ¥20 access多表提取相同字段数据并合并
    • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
    • ¥20 Java-Oj-桌布的计算