PHP:用 imagettftext 分解文本换行

发布于 2024-10-02 23:38:08 字数 2233 浏览 0 评论 0原文

该脚本获取文本、查找 url、为它们着色并生成 png 图像。我遇到的问题是自动换行。由于我必须将文本分开并将其重新组合在一起才能为链接着色,因此我很难弄清楚如何换行文本。这是脚本和结果图像。

// Matches urls
function is_a_url($text) {
    $isurl = preg_match("((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", $text) || preg_match("/@(\w+)/", $text) || preg_match("/#(\w+)/", $text);
    return $isurl;
}

// Set defaults
$image_width = 500;
$image_height = 110;
$start_x = 5;
$start_y = 20; // initial x/y coords of text
$fontsize = 14;
$font = './font.ttf';
$angle = 0;

$im = imagecreatetruecolor($image_width, $image_height);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 51, 51, 51);
$linkcolor = imagecolorallocate($im, 51, 210, 208);
$red = imagecolorallocate($im, 200, 0, 0);

// Create the box
imagefilledrectangle($im, 0, 0, $image_width, $image_height, $red);

// Get the text
$text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem http://somelongurl.com/then-we-make-it-super-long-with-some-more/ Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum http://www.shorturl.com/ Lorem Ipsum";

//split the text on spaces so we can eval each "word"
$string_chunks = explode(' ', $text);

// Takes the split and recombine
foreach ($string_chunks as $chunk) {
    //wrap based on image size
    if($start_x > $image_width){
        $start_x = 5;
        $start_y += 20;
    }
    else {
        $image_width = $image_width - 10;
        $output .= ($counter % 15 < 1) ? '\r' : '';
    }
   // get coordinates of bounding box containing text
   $coords = imagettfbbox($fontsize, $angle, $font, $chunk);

   $end_x = $coords[0] + $coords[4] + 10;

   // figure out which color to draw in
   $color_to_draw = is_a_url($chunk) ? $linkcolor : $black; 

   // draw the text chunk
   imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);


   // adjust starting coordinates to the END of the just-drawn text
   $start_x += $end_x;
}

// Save the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

替代文本 http://dl.dropbox.com/u/19973/script.png< /a>

This script takes text, looks for urls, colors those and makes a png image. The problem I am having is with wordwrap. Since I have to break the text apart and put it back together to color the links, I am having a hard time figuring out how to wrap the text. Here is the script and an image of the results.

// Matches urls
function is_a_url($text) {
    $isurl = preg_match("((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", $text) || preg_match("/@(\w+)/", $text) || preg_match("/#(\w+)/", $text);
    return $isurl;
}

// Set defaults
$image_width = 500;
$image_height = 110;
$start_x = 5;
$start_y = 20; // initial x/y coords of text
$fontsize = 14;
$font = './font.ttf';
$angle = 0;

$im = imagecreatetruecolor($image_width, $image_height);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 51, 51, 51);
$linkcolor = imagecolorallocate($im, 51, 210, 208);
$red = imagecolorallocate($im, 200, 0, 0);

// Create the box
imagefilledrectangle($im, 0, 0, $image_width, $image_height, $red);

// Get the text
$text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem http://somelongurl.com/then-we-make-it-super-long-with-some-more/ Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum http://www.shorturl.com/ Lorem Ipsum";

//split the text on spaces so we can eval each "word"
$string_chunks = explode(' ', $text);

// Takes the split and recombine
foreach ($string_chunks as $chunk) {
    //wrap based on image size
    if($start_x > $image_width){
        $start_x = 5;
        $start_y += 20;
    }
    else {
        $image_width = $image_width - 10;
        $output .= ($counter % 15 < 1) ? '\r' : '';
    }
   // get coordinates of bounding box containing text
   $coords = imagettfbbox($fontsize, $angle, $font, $chunk);

   $end_x = $coords[0] + $coords[4] + 10;

   // figure out which color to draw in
   $color_to_draw = is_a_url($chunk) ? $linkcolor : $black; 

   // draw the text chunk
   imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);


   // adjust starting coordinates to the END of the just-drawn text
   $start_x += $end_x;
}

// Save the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

alt text http://dl.dropbox.com/u/19973/script.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨落星ぅ辰 2024-10-09 23:38:08

我在换行文本方面遇到了类似的问题,所以我编写了一个小函数来帮助我解决这个问题,也许它也会对您有所帮助。所以这是函数:

function breakTextCentered($str,$num) {
        $strs = explode(' ',$str);
        $strlenMax = $num;

        foreach($strs as $item) {
            $strlenTemp += strlen(utf8_decode($item));
            $tempStr .= $item." ";
            if($strlenTemp>$strlenMax) {
                $ret .= $tempStr."\n";
                $strlenTemp =0;
                $tempStr = '';
            }
        }
        if($strlenTemp<=$strlenMax) {
            $ret .= $tempStr;
        }
        return $ret;
    }

只需传递文本和您想要在一行上显示的字符数。它只会在空格上换行文本。

I had similar problem with wrap text, so I wrote a little function that helps me with that, maybe it'll help you too. so here is the function:

function breakTextCentered($str,$num) {
        $strs = explode(' ',$str);
        $strlenMax = $num;

        foreach($strs as $item) {
            $strlenTemp += strlen(utf8_decode($item));
            $tempStr .= $item." ";
            if($strlenTemp>$strlenMax) {
                $ret .= $tempStr."\n";
                $strlenTemp =0;
                $tempStr = '';
            }
        }
        if($strlenTemp<=$strlenMax) {
            $ret .= $tempStr;
        }
        return $ret;
    }

just pass the text and the number of chars you want to appear on one line. it'll wrap text only on spaces.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文