2018년 5월 22일 화요일

[PHP예제] 144 이미지의 크기 및 정보 구하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>이미지의 크기 및 정보 구하기</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
require_once 'h.php';

$fileName = __DIR__ . '/test.jpg';
if( !file_exists($fileName) )
{
  die('파일이 존재하지 않음');
}

// 이미지 정보를 구함
$imageInfo = getimagesize($fileName);

// 이미지 정보를 표시
echo "<table>";
echo "<tr><td>파일이름</td>";
echo "<td>" . h($fileName) . "</td></tr>";
echo "<tr><td>폭</td>";
echo "<td>" . h($imageInfo[0]) . "</td></tr>";
echo "<tr><td>높이</td>";
echo "<td>" . h($imageInfo[1]) . "</td></tr>";
echo "<tr><td>종류(1:gif, 2:jpg, 3:png, 4:swf, 17:ico 등)</td>";
echo "<td>" . h($imageInfo[2]) . "</td></tr>";
echo "<tr><td>&lt;img&gt;태그에서 직접 이용할 수 있는 문자열</td>";
echo "<td>" . h($imageInfo[3]) . "</td></tr>";

if( isset($imageInfo['bits']) )
{
  echo "<tr><td>bits</td>";
  echo "<td>" . h($imageInfo['bits']) . "</td></tr>";
}

if( isset($imageInfo['channels']) )
{
  echo "<tr><td>channels(3:RGB, 4:CMYK)</td>";
  echo "<td>" . h($imageInfo['channels']) . "</td></tr>";
}

echo "<tr><td>MIME</td>";
echo "<td>" . h($imageInfo['mime']) . "</td></tr>";
echo "</table>";

$url = './128_display.php?file=' . rawurlencode(basename($fileName));
echo '<p><img src="' . h($url) . '" alt="사진"></p>';
?>
</div>
</body>
</html>



[PHP예제] 142 이미지에 텍스트 추가하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
// 기존의 이미지 파일을 설정함
$fileName = __DIR__ . '/test.jpg';
if( !file_exists($fileName) )
{
  die('파일이 존재하지 않음');
}

$image = imagecreatefromjpeg($fileName);

// 입력 요소를 설정함
// 글자 크기
$size = 24;

// 각도 설정(왼쪽에서 오른족으로 수평이0, 플러스: 좌표를 축으로 반시계 방향쪽)
$angle = 0;

// 좌표(왼쪽 위 모서리가 0, 0)
$x = 50;
$y = 50;

// 글자색을 설정
$textColor = imagecolorallocate($image, 128, 0, 0);

// 글꼴파일(적절하게 경로 설정)
$font = __DIR__ . '/NanumGothic.ttf';
if( !file_exists($font) )
{
  die('폰트 파일이 존재하지 않음');
}

// 텍스트를 추가함
$string = '테스트 글쓰기 Wooguy 81';
imagettftext($image, $size, $angle, $x, $y, $textColor, $font, $string);

// Content-Type 헤더를 전송함
header('Content-type: image/jpeg');
// IE가 Content-Type 헤더를 무시하지 않게 함
header('X-Content-Type-Optoins: nosniff');

imagejpeg($image);

// 이미지를 삭제하고 메모리 점유를 해제함
imagedestory($image);



  • 이미지에 점을 그리기
    • imagesetpixel()
      • 제2인수 - X좌표
      • 제3인수 - Y좌표
      • 제4인수 - 색
      • imagesetpixel($image, $x, $y, $color);



[PHP예제] 141 이미지의 섬네일을 생성하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
// 원본 파일의 파일명을 설정함.
$fileName = __DIR__ . '/images.jpg';
if( !file_exists($fileName) )
{
  die('파일이 존재하지 않음');
}

// 이미지의 크기를 가져옴
$imageSize = getimagesize($fileName);
$w = $imageSize[0];
$h = $imageSize[1];

// 섬네일의 폭을 100픽셀로 정하고 자동으로 높이를 산출
$newW = 100;
$newH = intval($newW / $w * $h);

// Content-Type 헤더를 전송함
header('Content-type: image/png');
// IE가 Content-Type 헤더를 무시하지 않게 함
header('X-Content-Type-Optoins: nosniff');

// 리샘플링을 진행함
$imgThumb = imagecreatetruecolor($newW, $newH);
$image = imagecreatefromjpeg($fileName);

// 성공한 경우 imagecopyresampled() 함수는 true를 되돌림
if( imagecopyresampled($imgThumb, $image, 0, 0, 0, 0, $newW, $newH, $w, $h) )
{
  imagepng($imgThumb);
}

// 이미지를 삭제하고 메모리 점유를 해제함
imagedestory($image);
imagedestory($imgThumb);




  • 이미지의 크기를 구하기
    • getimagesize()
      • getimagesize($fileName);
    • 이미지의 크기와 종류, 그리고 <img> 태그로 이용할 수 있는 크기 속성 문자열


[PHP예제] 138 이미지 생성 및 저장




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php
// Content-Type 헤더를 전송함
header('Content-type: image/png');
// IE가 Content-Type 헤더를 무시하지 않게 함
header('X-Content-Type-Optoins: nosniff');

// 이미지를 생성함
$image = imagecreatetruecolor(400, 300);

// 이미지의 배경색에 빨간색을 설정함
// 제2~4인수에 RGB의 각 값을 0~255의 정수로 지정함
$bg_color = imagecolorallocate($image, 255, 0, 0);
imagefill($image, 0, 0, $bg_color);

// 브라우저에 이미지를 출력함
imagepng($image);

// 이미지를 삭제하고 메모리 점유를 해제함
imagedestory($image);




  • 이미지를 파일로 저장하고 싶을 때
    • imagepng() 함수의 제2인수에 파일명을 지정하여 이미지를 파일에 저장
      • imagepng($image, $fileName)

2018년 5월 21일 월요일

[PHP예제] 136 CSV 파일을 읽음


read_csv.csv

,강사,과목
월요일,김철수,수학
화요일,이만수,과학
수요일,박춤,댄스
목요일,최고음,음악
금요일,구민철,사회
토요일,리차드,"영어1
영어2"
,,
,,
일요일,-,-


136.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>CSV 파일을 읽음</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
// h() 함수를 불러옴
require_once 'h.php';

// CSV 파일은 Windows의 엑셀에서 작성한 SJIS 인코드
$csvFile = './read_csv.csv';
if( !file_exists($csvFile) )
{
  die('파일이 존재하지 않음');
}

// 문자 깨짐 방지
// CSV 파일의 내용을 모두 넣음
$tempCSV = file_get_contents($csvFile);

// 문자 인코딩을 UTF-8로 변환함
$tempCSV = mb_convert_encoding($tempCSV, 'UTF-8', 'EUC-KR');

// 임시 파일에 저장함
$fp = tmpfile();
fwrite($fp, $tempCSV);

// 파일 포인터를 처음으로 되돌림
rewind($fp);

// 로케일을 설정함
setlocale(LC_ALL, 'ko_KR.UTF-8');


// 한 줄씩 읽고 표를 생성함
$html = '<table>';

while( $arr = fgetcsv($fp) )
{
  if( !array_diff($arr, array('')) )
  {
    continue;
  }

  list($day, $teacher, $subject) = $arr;

  // nl2br() 함수에서 요소 안의 줄 바꿈을 <br>로 변환함
  $html .= '<tr>'
    . '<td>' . nl2br(h($day), false) . '</td>'
    . '<td>' . nl2br(h($teacher), false) . '</td>'
    . '<td>' . nl2br(h($subject), false) . '</td>'
    . '</tr>';
}

$html .= '</table>';

// 파일의 잠금을 해제함
fflush($fp);
flock($fp, LOCK_UN);

// 파일을 닫음
fclose($fp);

// 브라우저에 출력함
echo $html;
?>
</div>
</body>
</html>




  • CSV 파일을 출력하고 싶을 때
    • fputcsv() 함수를 사용하여 배열 데이터를 CSV 파일에 기록함

[PHP예제] 128 디렉터리 안의 이미지를 목록으로 표시


128.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>디렉터리 안의 이미지를 목록으로 표시</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
// h() 함수
require_once 'h.php';

// 이미지를 목록으로 표시할 디렉터리를 설정
$dirName = __DIR__;
if( !is_dir($dirName) )
{
  die('디렉터리가 존재하지 않음');
}

echo "<p>디렉터리명(상대 경로) : $dirName <br>";
echo "절대 경로: " . realpath($dirName) . "</p>";
echo "<p>디렉터리 안의 이미지 목록</p>";

// 디렉터리를 확인
$dir = scandir($dirName);

// 디렉터리 안의 이미지를 목록으로 표시
foreach( $dir as $d )
{
  $path = $dirName . '/' . $d;

  // '.'에서 시작하는 항목과 디렉터리를 제외함.
  if( strpos($d, '.') === 0 || is_dir($path) )
  {
    continue;
  }

  // getimagesize() 함수에서 이미지 파일인지 확인
  if( @getimagesize($path) !== false )
  {
    // 확장자가 GIF, PNG, JPG의 이미지를 표시함
    $extension = pathinfo($path, PATHINFO_EXTENSION);

    if( !in_array($extension, array('gif', 'png', 'jpg', 'jpeg')))
    {
      continue;
    }

    $imageFile = '128_display.php?file=' . rawurlencode($d);

    echo '<a href="' . h($imageFile) . '" target="_blank">';
    echo '<img src="' . h($imageFile) . '" width="100" alt="사진">';
    echo "</a>&nbsp;";
  }
}
?>
</div>
</body>
</html>

128_display.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
// GET 쿼리를 통해 이미지 파일명을 받음
if( !isset($_GET['file']) )
{
  die('표시할 파일이 지정되어 있지 않음');
}
$fileName = basename($_GET['file']);

$dirName = __DIR__;
$subDirList = array('output' => 1); // 표시 가능한 디렉터리명 목록

// GET 쿼리에 디렉터리명이 지정되어 있으면 확인하여 추가함
if( isset($_GET['dir']) )
{
  if( !isset($subDirList[$_GET['dir']]) )
  {
    dir('잘못된 지정임');
  }

  $path = $dirName . '/' . $_GET['dir'] . '/' . $fileName;
}
else
{
  $path = $dirName . '/' . $fileName;
}

// 이미지를 출력함
if( file_exists($path) && ($imageSize = getimagesize($path)) !== false )
{
  // HTTP 헤더가 전송되지 않으면
  // 이미지를 단독 표시로 처리해 HTTP 헤더를 전송함
  if( !headers_sent() )
  {
    header('Content-Type: ' . $imageSize['mime']);

    // 인터넷 익스플로러가 Content-Type 헤더를 무시하지 않게 함
    header('X-Content-Type-Options: nosniff');
  }
  readfile($path);
}
else
{
  echo "이미지를 출력할 수 없음";
}


[PHP예제] 114 파일의 확장자를 구함 (파일과 디렉터리)



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>파일의 확장자를 구함</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
// 확장자를 구할 파일에 이 예제 파일을 설정
$fileName = basename(__FILE__);

// 파일이 있는지 확인
if( file_exists($fileName) )
{
  // 경로 정보를 구함
  $pathinfo = pathinfo($fileName);

  // 브라우저에 파일 확장자를 출력함
  echo $fileName . ' 의 확장자: ' . $pathinfo['extension'];
}
else
{
  echo "파일이 존재하지 않음";
}

?>
</div>
</body>
</html>




  • 파일명을 구할 때
    • $pathinfo['basename']
  • 파일이 있는지 확인
    • file_exists()
  • 파일이 읽기 가능한지 확인
    • is_readable()
  • 파일이 쓰기 가능한지 확인
    • is_writable()
  • 파일을 복사
    • copy()
      • copy($fromFile, $toFile)
  • 파일 삭제
    • unlink()
      • unlink($fileName)
  • 파일의 종류
    • finfo 객체
      • $finfo = new finfo(FILEINFO_MIME_TYPE);
    • MIME 타입을 구함
  • 디렉터리를 생성
    • mkdir()
  • 경로명에서 디렉터리명을 구함
    • dirname()
  • 절대 경로명을 구함
    • realpath()
  • 디렉터리에서 사용 가능한 용량을 구함
    • disk_free_space()
  • 디렉터리 삭제
    • rmdir()
  • 디렉터리 안의 디렉터리나 파일명을 구함
    • scandir()
      • $fileArrayAsc = scandir($dirName);
        print_r(h($fileArrayAsc));