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

개발강좌

프로그램 강좌 :
1. 유창화님의 썸네일, 정규표현식, 이미지관련 강좌
2. Sphinx 검색엔진을 이용한 도로명 주소 검색 시스템 구축

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

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

첨부파일

Daum_Regular.ttf (1.2M) 14회 다운로드 2014-08-01 09:28:41
image.lib.20140801.php (9.3K) 4회 다운로드 2014-08-01 09:28:41
study8.php (1.7K) 12회 다운로드 2014-08-01 09:28:41

본문


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

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

 

 

 

 

 

추천
3

댓글 2개

전체 53
개발강좌 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT