php
  • image
  • image-generation
  • 2014-10-08 96 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

    相關問題