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


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

강좌는 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 로 주어야 합니다.   

 

 

 

 

 

첨부파일

Daum_Regular.ttf (1.2 MB) 13회 2014-08-01 09:28
|

댓글 2개

좋아요 +1 누르고 갑니다~
감사합니다.
댓글을 작성하시려면 로그인이 필요합니다. 로그인

프로그램

+
제목 글쓴이 날짜 조회
11년 전 조회 1,379
11년 전 조회 681
11년 전 조회 1,258
11년 전 조회 731
11년 전 조회 1,434
11년 전 조회 1,187
11년 전 조회 1,985
11년 전 조회 3,648
11년 전 조회 3,147
11년 전 조회 3,610
11년 전 조회 1,374
11년 전 조회 1,599
11년 전 조회 2,313
11년 전 조회 1,011
11년 전 조회 1,421
11년 전 조회 3,559
11년 전 조회 2,288
11년 전 조회 690
11년 전 조회 1,253
11년 전 조회 1,147
11년 전 조회 798
11년 전 조회 2,930
11년 전 조회 1,410
11년 전 조회 1,270
11년 전 조회 660
11년 전 조회 2,983
11년 전 조회 2,879
11년 전 조회 713
11년 전 조회 3,407
11년 전 조회 827
11년 전 조회 722
11년 전 조회 1,013
11년 전 조회 823
11년 전 조회 633
11년 전 조회 1,057
11년 전 조회 1,773
11년 전 조회 1,010
11년 전 조회 775
11년 전 조회 622
11년 전 조회 2,386
11년 전 조회 1,933
11년 전 조회 2,471
11년 전 조회 1,399
11년 전 조회 2,678
11년 전 조회 3,096
11년 전 조회 4,429
11년 전 조회 5,778
11년 전 조회 2,119
11년 전 조회 1,693
11년 전 조회 1,429
11년 전 조회 1,095
11년 전 조회 838
11년 전 조회 1,019
11년 전 조회 910
11년 전 조회 1,390
11년 전 조회 2,192
11년 전 조회 869
11년 전 조회 1,046
11년 전 조회 1,707
11년 전 조회 1,396
11년 전 조회 1,281
11년 전 조회 1,206
11년 전 조회 1,122
11년 전 조회 3,472
11년 전 조회 1,120
11년 전 조회 1,720
11년 전 조회 1,988
11년 전 조회 1,296
11년 전 조회 1,285
11년 전 조회 1,279
11년 전 조회 740
11년 전 조회 1,137
11년 전 조회 1,480
11년 전 조회 1,443
11년 전 조회 815
11년 전 조회 1,160
11년 전 조회 928
11년 전 조회 1,683
11년 전 조회 1,325
11년 전 조회 700
11년 전 조회 2,134
11년 전 조회 6,602
11년 전 조회 1,267
11년 전 조회 1,111
11년 전 조회 1,043
11년 전 조회 897
11년 전 조회 1,431
11년 전 조회 829
11년 전 조회 3,388
11년 전 조회 1,234
11년 전 조회 1,628
11년 전 조회 999
11년 전 조회 2,635
11년 전 조회 1,268
11년 전 조회 2,554
11년 전 조회 1,921
11년 전 조회 2,431
11년 전 조회 1,381
11년 전 조회 2,511
11년 전 조회 1,321
🐛 버그신고