테스트 사이트 - 개발 중인 베타 버전입니다

이미지에 문자열을 그릴때 개행된 라인들까지도 정렬하기

· 11년 전 · 1427 · 2

대단할것은 없는 강좌이지만,
제 강좌를 출처를 밝히고 외부로 퍼가는 것은 허용하지만,
다른 강좌의 자료나 책의 자료로 사용되거나 부분적인 인용은 허용하지 않습니다.

강좌는 php 5. 대를 기준으로 하며, 이미지 관련을 다룹니다.
이미지에 글을 쓰거나 이미지를 합치거나 하는 등의 내용을 다루어 볼까 합니다.
나중에는 간단한 짤방 만들기 같은 것도 할수 있지 않을까 싶습니다.

이미지관련 > 이미지에 문자열을 그릴때 개행된 라인들까지도 정렬하기

 

이전 내용에서 위치에 따른 문자열을 그리는 것에 대해 다룬적이 있습니다.

이번 내용은 문자열이 여러 라인일때도 정렬이 되도록 하는 것을 다루었습니다.

 

전체 문자열을 하나의 문자열로 취급해서 그리면 전부 왼쪽에서 부터 그려지기 때문에

\n 을 기준으로 문자열을 잘라서 각각 처리하도록 하였으며,

각라인의 시작점을 뽑는 것이 문제의 핵심입니다. 

 

image.lib.20140801.php > 추가된부분

 

/*
생성된 이미지 리소스에 지정된 문자열을 원하는 위치에 imagefttext 를 사용하여 그림
image_text 와 다른 점은 center, right 일때 개행된 부분도 같이 정렬되도록 그림

$align = > left, center, right
$valign = > top, middle, bottom
$padding => 정렬될 위치로 얼마만큼 띄울것인가, int
$auto_newline => 전달받은 문자열이 이미지의 너비보다 클때 적절하게 잘라서 개행시켜줄지 여부, true 일때 적용

return true or false
*/
function image_text_align (&$image, $font_file, $font_size, $font_color, $angle, $text, $align='left', $valign='top', $padding=0, $auto_newline=true) {

    if (!is_resource($image))
        return false;

    $font_file = trim($font_file);
    if (!is_file($font_file))
        return false;

    $font_size = (float)$font_size;
    $font_color = (int)$font_color;
    $angle = (float)$angle;
    $align = trim($align);
    $valign = trim($valign);
    $padding = (int)$padding;

    if (!in_array($align, array('left', 'center', 'right')))
        $align = 'left';

    if ($align == 'left') {

        return image_text ($image, $font_file, $font_size, $font_color, $angle, $text, $align, $valign, $padding, $auto_newline);
    }

    if (!in_array($valign, array('top', 'middle', 'bottom')))
        $align = 'top';

    if ($auto_newline !== true)
        $auto_newline = false;

    $image_width = imagesx($image);//이미지의 너비
    $image_height = imagesy($image);//이미지의 높이



    //자동 개행
    if ($auto_newline === true) {

        $array = list($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4, $width, $height, $x_gap, $y_gap) = image_box_auto_newline ($font_file, $font_size, $angle, $text, $padding, $image_width);
    }
    else {

        $array = list($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4, $width, $height, $x_gap, $y_gap) = image_box ($font_file, $font_size, $angle, $text);
    }

    if (strstr($text, "\n") === false) {

        return image_text ($image, $font_file, $font_size, $font_color, $angle, $text, $align, $valign, $padding, $auto_newline);
    }

    $text_array = explode("\n", $text);

    $y_gap2 = 0;
    foreach($text_array as $k_ => $text_){

        $text_ = trim($text_);
        $array_ = list($x1_, $y1_, $x2_, $y2_, $x3_, $y3_, $x4_, $y4_, $width_, $height_, $x_gap_, $y_gap_) = image_box ($font_file, $font_size, $angle, $text_);

        if ($align == 'right') {//오른쪽

            $x = $image_width - $width_ + $x_gap_ - $padding;
        }
        else {//가운데

            $x = ceil(($image_width - $width_) / 2) + $x_gap_;
        }

        if ($valign == 'top') {//상단

            $y = $y1_ + $y_gap_ + $padding + $y_gap2;
        }
        else if ($valign == 'bottom') {//하단

            if ($k_ == 0)
                $y = $image_height + $y_gap_ - $padding - $height + $height_;
            else
                $y = $image_height + $y_gap_ - $padding - $height + $height_ + $y_gap2;
        }
        else {//가운데

            if ($k_ == 0)
                $y = ceil(($image_height + $height) / 2) + $y_gap_ - $height + $height_;
            else
                $y = ceil(($image_height + $height) / 2) + $y_gap_ - $height + $height_ + $y_gap2;
        }

        imagefttext($image, $font_size, $angle, $x, $y, $font_color, $font_file, $text_);

        $y_gap2 += $height_ + $y_gap_ + ceil($font_size * 0.5);
    }

    return true;
}

 

image_text 도 원래 고유기능으로 필요하기 때문에

image_text_align 이라는 함수를 추가하였습니다.

 

image_text_align (&$image, $font_file, $font_size, $font_color, $angle, $text, $align='left', $valign='top', $padding=0, $auto_newline=true) 

 

사용법은 기존 image_text 와 동일합니다.

 

if ($align == 'left') {

    return image_text ($image, $font_file, $font_size, $font_color, $angle, $text, $align, $valign, $padding, $auto_newline);
}
왼쪽 정렬을 사용할경우에는 굳이 문자열을 라인별로 쪼개서 처리할 필요가 없기 때문에 기존 함수로 return 시켰습니다.

 

if (strstr($text, "\n") === false) {

    return image_text ($image, $font_file, $font_size, $font_color, $angle, $text, $align, $valign, $padding, $auto_newline);
}
또, 문자열 자체가 한라인이라면 쪼개서 처리할 필요가 없기 때문에 역시 ​기존 함수로 return 시켰습니다.

 

$text_array = explode("\n", $text);

$y_gap2 = 0;
foreach($text_array as $k_ => $text_){

    $text_ = trim($text_);
    $array_ = list($x1_, $y1_, $x2_, $y2_, $x3_, $y3_, $x4_, $y4_, $width_, $height_, $x_gap_, $y_gap_) = image_box ($font_file, $font_size, $angle, $text_);

    if ($align == 'right') {//오른쪽

        $x = $image_width - $width_ + $x_gap_ - $padding;
    }
    else {//가운데

        $x = ceil(($image_width - $width_) / 2) + $x_gap_;
    }

    if ($valign == 'top') {//상단

        $y = $y1_ + $y_gap_ + $padding + $y_gap2;
    }
    else if ($valign == 'bottom') {//하단

        if ($k_ == 0)
            $y = $image_height + $y_gap_ - $padding - $height + $height_;
        else
            $y = $image_height + $y_gap_ - $padding - $height + $height_ + $y_gap2;
    }
    else {//가운데

        if ($k_ == 0)
            $y = ceil(($image_height + $height) / 2) + $y_gap_ - $height + $height_;
        else
            $y = ceil(($image_height + $height) / 2) + $y_gap_ - $height + $height_ + $y_gap2;
    }

    imagefttext($image, $font_size, $angle, $x, $y, $font_color, $font_file, $text_);

    $y_gap2 += $height_ + $y_gap_ + ceil($font_size * 0.5);
} 

라인별로 문자열을 짤라서 배열로 저장하고

양옆 공백을 제거한다음 top, middle, bottom 시 시작점 위치잡아 준 다음

개별적으로 하나씩 문자열을 그려나가는 부분입니다. 

 

ceil($font_size * 0.5) 은 기본적인 line-height 값이라고 보시면 됩니다.

 

예제8 > study8.php

 

<?php

@error_reporting( E_ALL );
header("Content-Type: text/html; charset=UTF-8");

include_once('image.lib.20140801.php');



$font_file = './Daum_Regular.ttf';
$font_size = 15;
$angle = 0;
$text = '동해물과 백두산이 마르고
닳도록 하느님이
보우하사 우리
나라 만세';
$padding = 10;

$array = list($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4, $width, $height, $x_gap, $y_gap) = image_box ($font_file, $font_size, $angle, $text);

?>

폰트파일 : <?php echo $font_file; ?><br>

폰트크기 : <?php echo $font_size; ?> px<br>

기울기 : <?php echo $angle; ?><br>

문자열 : <?php echo nl2br($text); ?><br>

패딩 : <?php echo $padding; ?> px<br>
<br>

<?php

$aligns = Array('left', 'center', 'right');
$valigns = Array('top', 'middle', 'bottom');

$i = 1;
foreach($aligns as $align){

    foreach($valigns as $valign){

        $im = imagecreatetruecolor(300, 300);
        $red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
        $blue = imagecolorallocate($im, 0x00, 0x80, 0xFF);
        $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
        $black = imagecolorallocate($im, 0x00, 0x00, 0x00);
        $gray = imagecolorallocate($im, 0XD0, 0XD0, 0XD0);

        imagefilledrectangle($im, 0, 0, 299, 299, $gray);

        image_text_align ($im, $font_file, $font_size, $black, $angle, $text, $align, $valign, $padding);

        imagepng($im, 'temp/study8_' . $i . '.png');
        imagedestroy($im);

        ?>

        <br><br>
        <strong><?php echo $align; ?>,  <?php echo $valign; ?></strong><br>

        <img src='temp/study8_<?php echo $i; ?>.png?<?php echo time(); ?>'>
        <br><br>

        <?php

        $i++;
    }
}

?>

 

 

 

예제를 실행할 때에는 temp 디렉토리를 생성하고 퍼미션을 777 로 주어야 합니다.   

 

 

 

 

 

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 2개

11년 전
좋아요 +1 누르고 갑니다~
감사합니다.

게시글 목록

번호 제목
26560
24588
31642
31638
31633
31630
31625
19452
6719
6718
6717
6715
27797
30907
30904
6714
6713
27791
19450
6712
6711
6709
6708
27790
19447
6706
6703
6702
6701
6697
6692
27783
6691
6687
6685
6683
6682
19446
27770
19445
27768
6681
6675
6674
19444
6672
6671
27761
6670
30900
24585
6660
6655
6653
31624
6651
31623
31621
19443
6650
31620
31619
31612
31611
27746
31605
6648
20781
31603
31600
6645
6643
6642
6640
20777
31597
6637
19442
31594
31591
31589
31586
31584
20758
19440
31575
31567
20747
6636
31563
31552
27743
24579
6630
6628
6620
6617
27732
24577
6616