2014-11-15 3 views
1

문자열을 문자열 이미지로 변환하려면 imagettftextimageTTFBbox을 사용하고 있습니다. 예를 들어왜 내 마지막 단어가 잘리지 않습니까?

,

이 행성이 아래에이 문자열 - 또는 오히려이 있었다 -이이었다 문제 : 거기에 사는 사람들의 대부분은 거의 모든 시간을 위해 불행을. 이 문제에 대한 많은 해결책이 제안되었지만, 대부분은 작은 초록색 종이의 움직임에 크게 관심이있었습니다. 그 이유는 전체적으로 불만 인 작은 초록색 종이가 아니기 때문에 이상했습니다.

은 마지막 줄 정도가 차단되고, 그러나

img

된다.

내 설정은 다음과 같이 구성 래퍼 함수는 텍스트 (완벽하게 잘 작동), 아래 그림있어 주요 img2Text 기능을 포장 :

function imagettfJustifytext($text, $font="../../fonts/Roboto-Light.ttf", $Justify=2, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){ 
    $angle = 0; 
    $L_R_C = $Justify; 
    $_bx = imageTTFBbox($fsize,0,$font,$text); 

    $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W; 
    $H = ($H==0)?abs($_bx[5]-$_bx[3]):$H; 

    $im = @imagecreate($W, $H) 
    or die("Cannot Initialize new GD image stream"); 

    $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]); 
    $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); 

    if($L_R_C == 0){ //Justify Left 
     imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text); 
    } elseif ($L_R_C == 1) { //Justify Right 
     $s = split("[\n]+", $text); 
     $__H=0; 
     foreach($s as $key=>$val){ 
      $_b = imageTTFBbox($fsize,0,$font,$val); 
      $_W = abs($_b[2]-$_b[0]); 
      $_X = $W-$_W; 
      $_H = abs($_b[5]-$_b[3]); 
      $__H += $_H;    
      imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);  
      $__H += 6; 
     } 
    } elseif ($L_R_C == 2) { //Justify Center 
     $s = split("[\n]+", $text); 
     $__H=0; 
     foreach($s as $key=>$val){ 
      $_b = imageTTFBbox($fsize,0,$font,$val); 
      $_W = abs($_b[2]-$_b[0]); 
      $_X = abs($W/2)-abs($_W/2); 
      $_H = abs($_b[5]-$_b[3]); 
      $__H += $_H;    
      imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);  
      $__H += 6; 
     } 
    }   
    return $im; 
    } 

나는 문제가 내장 imageTTFBox에있다 생각 함수 또는 그것을 사용하여 이미지의 높이를 계산합니다. 긴 텍스트 문자열로 높이를 과소 평가하는 것 같습니다. 참조

$H = ($H==0)?abs($_bx[5]-$_bx[3]):$H; 

:

$_bx = imageTTFBbox($fsize,0,$font,$text); 

및 미숙 imageTTFBbox

array imagettfbbox (float $size , float $angle , string $fontfile , string $text) 

이 함수 계산 코드 관련 라인 I 편의상 이하 재현 line 6이며 트루 타입 텍스트의 경계 상자를 픽셀 단위로 반환합니다.

편집

timclutton의 대답은 의미가, 그리고 나는 $__H += 6; 라인을 제거하는 시도하고 그것은 도움을 않습니다. 이제 마지막 비트 만 끊어집니다. 이미지가 imagettfbbox()에 의해 반환되는 크기에 따라 함수의 시작 부분에서 만들었지 만 다음 foreach 루프의 끝에서 당신은 '라인 간격을'의 추가됩니다

img2

답변

2

(아래 이미지 참조) +6 통해 $__H += 6;. 이로 인해 세로 텍스트 크기가 원래 측정 된 차원을 넘어서서 증가합니다.

해당 줄을 제거하고 텍스트가 이미지에 맞게 표시되는지 테스트하여이를 테스트 할 수 있습니다.

줄 간격을 추가하려면 함수의 시작 부분에 변수를 만들고 imagettfbbox()에 의해 반환 된 치수와 줄 수를 곱한 값을 기준으로 이미지를 만들어야합니다 .

function imagettftextalign($text, $align = 0, $fsize = 12, $color = array(0x0, 0x0, 0x0), $bgcolor = array(0xFF, 0xFF, 0xFF), $font = './font/Roboto-Light.ttf', $angle = 0) 
{ 
    // measure input text. 
    $box = imagettfbbox($fsize, $angle, $font, $text); 
    $w = abs($box[2] - $box[0]); 
    $h = abs($box[5] - $box[3]); 

    // create resources. 
    $im = imagecreatetruecolor($w, $h); 
    $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]); 
    $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); 

    // set background. 
    imagefilledrectangle($im, 0, 0, $w, $h, $background_color); 

    // split text by line and get line height. 
    $lines = explode("\n", $text); 
    $lh = floor($h/count($lines)); 

    // output lines. 
    $y = ($lh * .8); // note: this is a guesstimate at the font baseline! 
    foreach ($lines as $line) { 
     if ($align > 0) { 
      $box = imagettfbbox($fsize, $angle, $font, $line); 
      $lw = abs($box[2] - $box[0]); // line width. 
      switch ($align) { 
       case 1: // centre. 
        $x = ($w/2) - ($lw/2); 
        break; 
       case 2: // right. 
        $x = $w - $lw; 
        break; 
      } 
     } else { 
      $x = 0; 
     } 

     imagettftext($im, $fsize, $angle, $x, $y, $text_color, $font, $line); 
     $y += $lh; // increment line y position. 
    } 

    return $im; 
} 

$txt = "This planet has — or rather had — a problem, which 
was this: most of the people living on it were unhappy 
for pretty much all of the time. Many solutions were 
suggested for this problem, but most of these were 
largely concerned with the movement of small green 
pieces of paper, which was odd because on the whole 
it wasn't the small green pieces of paper that were 
unhappy."; 

$im = imagettftextalign($txt, 1); 

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

이 나에게 당신이 목표로하는 무엇을 것 같다 다음과 같은 출력을 제공합니다 :


나는 다음과 같은 기능을 다시 한

example of function output

+0

를 @ 휴이 이것에 대한 의견이 있으십니까? – timclutton

+0

지연에 대해 사과드립니다. 나는 그것을 시도하고 도움이됩니다! (예! 내 편집 참조) – Huey

+1

@Huey 제 편집을 참조하십시오. – timclutton

관련 문제