dousi2013 2016-03-08 20:52
浏览 36
已采纳

使用php将文本写入图像

I have this task working great! I have successfully wrote text to an image then displayed the image using php, however the problem I'm running into is getting the font size perfect and to fit within a contained area. Im using imagettftext()

I'm getting this to work however when i move the text to the desired location im manually changing the font to then get it to fit. I would like to text to perfectly fill a "box" inside the image.

Here is my code

Main.php

    check out the promo code below<br />

    <img src="imagem.php?promo=DISH120" alt="" />

imagem.php $font = 'font-type.ttf';

    $rImg = ImageCreateFromJPEG( "test.jpg" );

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

    imagettftext($rImg, 20, 0, 660, 130, $color, $font, urldecode($_GET['promo']));

    header('Content-type: image/jpeg');
    imagejpeg($rImg, NULL,100);

Here is the image im writing image

i want the text to write to the bottom right next to code, however when i make the font big enough to match the CODE height it way to wide.

ADDITION

 <?php 
function makeTextBlock($text, $fontfile, $fontsize, $width) 
{    
    $words = explode(' ', $text); 
    $lines = array($words[0]); 
    $currentLine = 0; 
    for($i = 1; $i < count($words); $i++) 
    { 
        $lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $words[$i]); 
        if($lineSize[2] - $lineSize[0] < $width) 
        { 
            $lines[$currentLine] .= ' ' . $words[$i]; 
        } 
        else 
        { 
            $currentLine++; 
            $lines[$currentLine] = $words[$i]; 
        } 
    } 

    return implode("
", $lines); 
} 
?>

I found this function re formats a text string into a text block of a given width, this is kinda what im trying to achieve however, im not sure how to integrate this. I want a box which width and height never change that will be filled with text that its character count will change.

  • 写回答

1条回答 默认 最新

  • donglao7947 2016-03-08 21:05
    关注

    This sounds like an issue with the font you're using. Try to make sure that the font matches the font of the text in the image, so that when you increase the size of the font to fit the image, it doesn't go too wide.

    Other things I'd point out:

    1. Based on what you're doing, I don't recommend a $_GET parameter.
    2. You should remove the image from memory once you're done with it, like this: imagedestroy($rImg);
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?