에디터에 base64 이미지 가져오면 png로 저장하여 주는 거 > 그누보드5 팁자료실

그누보드5 팁자료실

에디터에 base64 이미지 가져오면 png로 저장하여 주는 거 정보

에디터에 base64 이미지 가져오면 png로 저장하여 주는 거

본문

welcome 님이 미완성으로 둔 거 수정해 봤습니다. 원글은 이거..   https://sir.kr/g5_tip/21124

그냥 적용해 봤더니 그림 파일이 폭주하더군요... 저도 이 기능이 꼭 필요해서...  화면을 shift-win-s 해서 crop 해서 clipboard 넣었다가 에디터에 ctrl-v 해서 붙여 넣어서 쓸 때 쓰는 겁니다. 화면을 캡쳐해서 그림판 열어서 png로 저장하고 그림 불러넣고 하는 절차를 줄여줍니다.

 

별로 수정한 건 없습니다. 거의 그대롭니다.

 

{그누보드5 root}/extend/user.config.php 에 아래 내용 들어가고,,, 보시면 base64_to_file()은 welcome님 쓰신거 그대로고, base64_content_image() 부분만 약간 손봤습니다. preg_match 대신 preg_match_all 하면 한번에 내부 base64 이미지 전부 찾을 수 있긴 할텐데, 큰 차이는 없을거 같아서 그냥 loop 돌렸습니다. 어차피 preg_match_all 도 하나 찾고 다음에서 또 찾아가는 거니 뭐... 

 

<?php
function base64_to_file($base64_string, $extension) {
    $ym = date('ym', G5_SERVER_TIME);
    $data_dir = G5_DATA_PATH.'/editor/'.$ym;
    $data_url = G5_DATA_URL.'/editor/'.$ym;
    if(!is_dir($data_dir)) {
        @mkdir($data_dir, G5_DIR_PERMISSION);
        @chmod($data_dir, G5_DIR_PERMISSION);
    }
    $filename = basename($path);
    $chars_array = array_merge(range(0,9), range('a','z'), range('A','Z'));
    shuffle($chars_array);
    $shuffle = implode('', $chars_array);
    $file_name = abs(ip2long($_SERVER['REMOTE_ADDR'])).'_'.substr($shuffle,0,8).'_'.replace_filename($filename);
    $save_dir = sprintf('%s/%s', $data_dir, $file_name.".".$extension);
    $save_url = sprintf('%s/%s', $data_url, $file_name.".".$extension);    
    
    // open the output file for writing
    $ifp = fopen( $save_dir, 'wb' ); 
    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );
    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );
    // clean up the file resource
    fclose( $ifp ); 
    return $save_url; 
}

function base64_content_image($content) {
    if(!$content) return;
    $content = stripslashes($content);
    $pattern = "#data:image/(gif|png|jpeg);base64,([\w=+/]++)#";
	while( true ) {
		preg_match($pattern, $content, $match);
		if (isset($match[0]))
		{
			// 이미지 데이터
			$imgdata = $match[0];
			// 확장자
			$extension = explode(";", explode("/", $match[0])[1])[0];        
			$image = base64_to_file($imgdata, $extension); 
			//$image = "<p><img src='".$image."'></p>";
			if ($image) {
				$content = str_replace($match[0], $image, $content);
			}
		}
		else break;
	}
    $content = addslashes($content);
    return $content;
}

?>

 

 

그리고, 저는 basic 테마를 쓰고 있어서, welcome 님은 무슨 skin 파일을 수정하라고 하셨는데, 그걸 저는 찾을 수가 없어서...  {그누보드5 root}/bbs/write_update.php를 수정했습니다.

 

원래는 아래...

if (isset($_POST['wr_content'])) {
    $wr_content = substr(trim($_POST['wr_content']),0,65536);
    $wr_content = preg_replace("#[\\\]+$#", "", $wr_content);
}

 

제가 수정한 건 ...

if (isset($_POST['wr_content'])) {
	$wr_content = trim($_POST['wr_content']);
	$wr_content = preg_replace("#[\\\]+$#", "", $wr_content);
	$wr_content = base64_content_image($wr_content);
	$wr_content = substr($wr_content,0,65536);
}

 

base64로 이미지가 많이 들어갔는데 거기서 먼저 substr으로 65536까지만 빼버리면 혹시나 그림이 잘릴지도 모르고 해서 순서를 좀 바꿨습니다.

 

그랬더니 그림도 잘 올라가고, 잘 됩니다.

 

 

 

 

 

추천
4
  • 복사

댓글 3개

© SIRSOFT
현재 페이지 제일 처음으로