많이 사용하는 html을 이미지로 만들어 사용할 수 있는 라이브러리 입니다.
사용해보니 제가 본것에서는 아래와 같은 것이 있었습니다.
<?php
if ( $_POST['mode'] == "img_upload" )
{
$img_base64 = $_POST['img_base64'];
$img = str_replace('data:image/jpeg;base64,', '', $img_base64 );
$img = str_replace(' ', '+', $img);
$img_data = base64_decode($img);
$fExt = ( stristr($img_base64, 'data:image/jpeg') ) ? 'jpg':'png';
$imgFile = 'upfile/test.' . $fExt;
$imgSize = file_put_contents($imgFile, $img_data);
$oJson = (object)[];
$oJson->imgSize = $imgSize;
$oJson->imgFile = $imgFile;
$oJson->imgXY = $_POST['img_size_xy'];
$json_data = json_encode($oJson);
echo $json_data;
exit;
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ajax file upload </title>
</head>
<body>
<div id="html_canvas_test" style="border: 1px solid #ff1212;">
<input type="file" id="btn_file1">
<img src="googlelogo_color_272x92dp.png">
</div>
<p></p>
<button id="btn_test">버튼 클릭</button>
</body>
</html>
<script>
$(document).ready(function() {
$( "#btn_test").click(function(e)
{
// jpg로 주면 안되며 명확하게 jpeg로 줘야 한다
html2canvas( $("#html_canvas_test")[0] ).then(function(canvas) {
var img_base64 = canvas.toDataURL("image/jpeg");
// console.log(img_base64);
ajax_file_upload( img_base64 );
});
// 투명 png 테스트 된것
// html2canvas( $("#html_canvas_test")[0], {backgroundColor: null}
// ).then(function(canvas) {
// var img_base64 = canvas.toDataURL("image/png");
// ajax_file_upload( img_base64 );
// });
});
/**
* ajax post
*
* @param mixed img_base64
*
* @return [type]
*
*/
function ajax_file_upload( img_base64 )
{
// 단순 크기를 보기 위한것
let img_width = $('#html_canvas_test').outerWidth();
let img_height = $('#html_canvas_test').outerHeight();
let img_size_xy= img_width + 'x' + img_height;
console.log('img size:', img_size_xy);
//
let form = new FormData();
form.append( "mode", 'img_upload' );
form.append( "img_base64", img_base64 );
form.append( "img_sizeXY", img_size_xy );
console.log(img_size_xy);
jQuery.ajax({
url : "hh.php"
, type : "POST"
, processData : false
, contentType : false
, data : form
, success:function(response) {
// console.log(response);
resultData = JSON.parse(response);
console.log(resultData);
}
,error: function (jqXHR) {
console.log(jqXHR.responseText);
}
});
}
});
</script>
위에서 png 부분에서 투명으로 하고 싶으면 예제 처럼 옵션을 추가해 줘야 합니다. 그렇지 않으면 투명이 아니라 힌색으로 디폴트로 채워집니다. 현재 테스트한 최신 버전에선 그렇습니다.
그리고 이미타입에서 image/jpg 가 아닙니다. jpeg로 반드시 표준에 맞게 해줘야 합니다. 그래야 정상적으로 작동이 됩니다. 이 경우는 없는 이미지 타입이라서 png로 되었던 기억입니다.
서버로 보낼때는 파일로 보내는것이 아니기 때문에 ajax에서 enctype에 대한 언급은 없습니다.
post로 넘기고 이것은 base64 이기 때문에 서버에서 받아서 불필요한것 삭제 후 디코딩하여 사용 합니다.
결과를 json으로 출력하기 때문에 개발자 도구에서 보면 json 결과를 볼 수 있습니다.