php
  • image
  • image-generation
  • 2014-10-08 99 views 0 likes 
    0

    我有几行代码来生成一个普通的图像与一些给定的文字在PHP中。但是,当我给图像文字的宽度超出图像。如何将图像内的文字与固定宽度但动态高度对齐?我的代码如下。如何在PHP中自动将文本与图像对齐?

    header ("Content-type: image/png"); 
    $string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s';            
    $font = 4; 
    $width = ImageFontWidth($font) * strlen($string); 
    $height = ImageFontHeight($font); 
    
    $im = @imagecreate (200,500); 
    $background_color = imagecolorallocate ($im, 255, 255, 255); //white background 
    $text_color = imagecolorallocate ($im, 0, 0,0);//black text 
    imagestring ($im, $font, 0, 0, $string, $text_color); 
    imagepng ($im); 
    

    我希望这个图像根据给定的段落自动调整文本。怎么做?

    +0

    我有这么多的麻烦做的是,在其他项目由于字母间距和每个字母的宽度,你不能以可接受的方式做到这一点。用PHP创建图像,你可以做的是用文本创建一个简单的html文件,然后使用phantomjs截图并在该文件夹中创建图像。这将是最简单的方式来相信我。 phantomjs非常简单,可以在几秒钟内完成你所要求的任何事情。这是你需要的:http://phantomjs.org/screen-capture.html – artuc 2014-10-08 12:54:59

    回答

    1

    你可以试试这个: (基于甘农的在http://php.net/manual/en/function.imagestring.php贡献)

    header ("Content-type: image/png"); 
    $string = "Lorem Ipsum is simply dummy\n text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s"; 
    $im = make_wrapped_txt($string, 0, 4, 4, 200); 
    imagepng ($im); 
    
    function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) { 
        if (strlen($color) != 6) $color = 000000; 
        $int = hexdec($color); 
        $h = imagefontheight($font); 
        $fw = imagefontwidth($font); 
        $txt = explode("\n", wordwrap($txt, ($w/$fw), "\n")); 
        $lines = count($txt); 
        $im = imagecreate($w, (($h * $lines) + ($lines * $space))); 
        $bg = imagecolorallocate($im, 255, 255, 255); 
        $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int); 
        $y = 0; 
        foreach ($txt as $text) { 
        $x = (($w - ($fw * strlen($text)))/2); 
        imagestring($im, $font, $x, $y, $text, $color); 
        $y += ($h + $space); 
        } 
        return $im; 
    } 
    

    给予这种结果:

    enter image description here

    +0

    这真棒。谢谢。现在我可以根据我的要求对其进行修改。需要一个想法。 :) – 2014-10-09 07:19:04

    +0

    只有一个疑问。我怎样才能使用一些自定义字体。如果我将该字体文件保存在根文件夹中,那么我怎么能在这里包含? – 2014-10-09 07:31:42

    +0

    只需使用$ my_font = imageloadfont('./ your_font.gdf');然后imagestring($ im,$ my_font ... – Yoric 2014-10-09 07:38:01

    相关问题