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

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


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

강좌는 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개

좋아요 +1 누르고 갑니다~

게시글 목록

번호 제목
8050
8048
19969
19968
19967
19966
19965
19964
19963
19962
19961
28345
31017
19960
19959
19958
19957
8039
8035
8029
28344
28339
8019
28338
8017
8010
8007
8004
8003
28332
28322
7999
28317
20956
7992
20945
28314
20936
20931
7986
20925
7982
7979
7978
7975
28307
7973
7966
28305
7963
28300
7961
28297
28295
7959
19948
19947
28292
31016
19946
19945
28286
7958
7956
7952
7946
28285
28283
19943
7944
7936
7931
28279
24666
24663
7928
7923
19941
28274
28257
28249
28248
7914
7912
7911
20912
7908
31755
28233
28232
28228
7903
28217
20900
24662
20891
20882
19936
20853
31011