在图像PHP上包装文本

时间:2016-10-28 02:48:13

标签: php

我希望有人可以帮助我,我需要将我的TEXT / STRING定位到图像底部的添加边框并将其打包或格式化。

这是我的代码:

$url

我在当前代码中获得此输出: Screenshot

2 个答案:

答案 0 :(得分:2)

您已经绘制了一个黑色10x10x10x140px边框。在接下来的步骤中,您将必须实现类似于以下(伪代码)的算法:

// Calculate the maximum number of characters per line
max_line_chars := floor(width / character_width)

// Calculate the maximum number of lines that will fit the bottom area
max_lines := floor(bottom_black_area_height / character_height)

// Build an array of wrapped lines
lines = get_array_of_word_wrapped_lines(string, max_line_chars)

// Shrink `lines` to the size of maximum number of lines, if necessary
if length_of lines > max_lines then
  lines := shrink(lines, max_lines)
  height_offset := 0
else
  height_offset := floor(((max_lines - length_of lines)) * character_height) / 2)
endif

for line in lines
  line_width := character_width * length_of line

  x := floor((image_width_with_borders - line_width) / 2)
  y := floor(height_of_image + 2 * border_width + height_offset)

  draw_line(x, y, line)

  height_offset := height_offset + character_height
endfor

实施例

$add = 'test.jpg';
$string = 'My people will live in peaceful dwelling places, in secure homes, in undisturbed places of rest. Isaiah 32:17-18';
$string_len = strlen($string);
$split_words = false;

$im = imagecreatefromjpeg($add);
$width  = imagesx($im);
$height = imagesy($im);

$border         = 10;
$width_delta    = 2 * $border;
$height_delta   = 15 * $border;
$img_adj_width  = $width + $width_delta;
$img_adj_height = $height + $height_delta;

$newimage = imagecreatetruecolor($img_adj_width, $img_adj_height);
$border_color = imagecolorallocate($newimage, 0, 0, 0);
imagefilledrectangle($newimage, 0, 0,
  $img_adj_width, $img_adj_height, $border_color);
imagecopyresized($newimage, $im, $border, $border, 0, 0,
  $width, $height, $width, $height);

$color = imagecolorallocate($newimage, 255, 255, 255);

$font = 4;
$font_width  = imagefontwidth($font);
$font_height = imagefontheight($font);

$max_line_chars = floor($width / $font_width);
$max_lines      = floor(($height_delta - 2 * $border) / $font_height);

$lines = explode(PHP_EOL, wordwrap($string, $max_line_chars, PHP_EOL, false));
if (count($lines) > $max_lines) {
  $lines = array_slice($lines, 0, $max_lines);
  $height_offset = 0;
} else {
  $height_offset = floor((($max_lines - count($lines)) * $font_height) / 2);
}

foreach ($lines as $line) {
  $line_width = $font_width * strlen($line);

  $x = floor(($img_adj_width - $line_width) / 2);
  $y = floor($height + $border * 2 + $height_offset);

  imagestring($newimage, $font, $x, $y, $line, $color);

  $height_offset += $font_height;
}

imagejpeg($newimage);

注意,wordwrap函数以及substr等标准字符串函数不支持Unicode!对于Unicode,您需要实现自己的wordwrap版本,并使用multi-byte string functions代替。

示例输出

Sample output

答案 1 :(得分:0)

$position_middle - 行更改为$position_middle = ceil(($height + ($text_height * 4.5)));,看看是否能解决问题。