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


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

강좌는 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,373
11년 전 조회 678
11년 전 조회 1,255
11년 전 조회 725
11년 전 조회 1,431
11년 전 조회 1,185
11년 전 조회 1,984
11년 전 조회 3,647
11년 전 조회 3,146
11년 전 조회 3,610
11년 전 조회 1,371
11년 전 조회 1,598
11년 전 조회 2,307
11년 전 조회 1,010
11년 전 조회 1,417
11년 전 조회 3,554
11년 전 조회 2,285
11년 전 조회 689
11년 전 조회 1,248
11년 전 조회 1,145
11년 전 조회 794
11년 전 조회 2,927
11년 전 조회 1,406
11년 전 조회 1,267
11년 전 조회 658
11년 전 조회 2,982
11년 전 조회 2,877
11년 전 조회 712
11년 전 조회 3,405
11년 전 조회 824
11년 전 조회 720
11년 전 조회 1,010
11년 전 조회 820
11년 전 조회 630
11년 전 조회 1,054
11년 전 조회 1,771
11년 전 조회 1,009
11년 전 조회 772
11년 전 조회 618
11년 전 조회 2,383
11년 전 조회 1,931
11년 전 조회 2,468
11년 전 조회 1,397
11년 전 조회 2,675
11년 전 조회 3,094
11년 전 조회 4,426
11년 전 조회 5,775
11년 전 조회 2,117
11년 전 조회 1,691
11년 전 조회 1,425
11년 전 조회 1,091
11년 전 조회 836
11년 전 조회 1,017
11년 전 조회 905
11년 전 조회 1,388
11년 전 조회 2,188
11년 전 조회 867
11년 전 조회 1,043
11년 전 조회 1,703
11년 전 조회 1,395
11년 전 조회 1,278
11년 전 조회 1,203
11년 전 조회 1,121
11년 전 조회 3,470
11년 전 조회 1,117
11년 전 조회 1,719
11년 전 조회 1,986
11년 전 조회 1,292
11년 전 조회 1,282
11년 전 조회 1,275
11년 전 조회 738
11년 전 조회 1,136
11년 전 조회 1,478
11년 전 조회 1,437
11년 전 조회 813
11년 전 조회 1,157
11년 전 조회 923
11년 전 조회 1,681
11년 전 조회 1,319
11년 전 조회 697
11년 전 조회 2,133
11년 전 조회 6,598
11년 전 조회 1,263
11년 전 조회 1,107
11년 전 조회 1,041
11년 전 조회 895
11년 전 조회 1,428
11년 전 조회 827
11년 전 조회 3,385
11년 전 조회 1,229
11년 전 조회 1,624
11년 전 조회 996
11년 전 조회 2,629
11년 전 조회 1,266
11년 전 조회 2,552
11년 전 조회 1,918
11년 전 조회 2,428
11년 전 조회 1,375
11년 전 조회 2,509
11년 전 조회 1,319
🐛 버그신고