JCROP을 이용한 업로드한 크롭( CROP ) 하기


 

Jcrop 다운 : 

Jcrop API : 

GitHub : 

 

 

 

 

■ JCROP을 이용한 업로드한 크롭( CROP ) 하기

 

 

 

 

웹 브라우저 상에서 이미지를 업로드하고, 해당 이미지를 편집 하는 기능을 제작하게 되었다.

 

HTML5의 캔버스를 통해 업로드한 이미지를 똑같이 복사하여, 작업영역을 만들고.

 

캔버스에서 작업이 완료된 그림을 다시 원본 이미지와 교체하는형태로 서버에 업로드 하지 않고 작업하는것을 마무리 하였다.

 

 

 

# 소스코드

<html>
<head>
<meta charset="UTF-8">
<title>:: JavaScript 캔버스 이미지 업로드 ::</title>
<meta name="viewport" content="width=device-width">
<link type="text/css" rel="stylesheet" href="./css/modern.css"/>
<link type="text/css" rel="stylesheet" href=""/>
<style type="text/css">
    .imgArea { text-align:center; }
    canvas, #uploadFile, #editBtn, #cutBtn { display:none; }
    body { overflow:hidden };
</style>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">


    let jcropApi = null;


    // @breif 이미지 크롭 영역지정 UI 나타내기
    function imgCropDesignate() {


        let editWidth = jQuery("#editImg").width();
        let editHeight = jQuery("#editImg").height();
       
        // @breif jcrop 실행시 크롭영역을 미리 세팅
        let x1 = window.screen.width / 2 - editWidth;
        let y1 = window.screen.height / 2 - editHeight;
        let x2 = editWidth / 1.5;
        let y2 = editHeight / 1.5;


        // @breif jcrop 실행
        jQuery("#editImg").Jcrop({
              bgFade : true
            , bgOpacity : .2
            , setSelect : [ x1, y1, x2, y2 ]
            , onSelect : updateCoords
        }, function() {
            jcropApi = this;
        });
        
        jQuery("#editBtn").css("display", "none");
        jQuery("#cutBtn").css("display", "inline");
    }
    
    // @breif 지정된 크롭 한 영역( 좌표, 넓이, 높이 )의 값을 보관하는 함수
    function updateCoords(crap) {
        jQuery("#xAxis").val(crap.x);
        jQuery("#yAxis").val(crap.y);
        jQuery("#wLength").val(crap.w);
        jQuery("#hLength").val(crap.h);
    }


    // @breif 크롭한 영역 잘라내고 추출하기
    function imgCropApply() {


        if(parseInt(jQuery("#wLength").val()) == "NaN") {
            alert("이미지를 크롭한 이후\n자르기 버튼을 클릭하세요.");
            return false;
        } else {


            let editImage = new Image();
            editImage.src = jQuery("#editImg").attr("src");


            editImage.onload = function() {


                // @breif 캔버스 위에 이미지 그리기
                let canvas = document.querySelector("canvas");
                let canvasContext = canvas.getContext("2d");


                // @breif 캔버스 크기를 이미지 크기와 동일하게 지정
                canvas.width = jQuery("#wLength").val();
                canvas.height = jQuery("#hLength").val();
                                
                canvasContext.drawImage(
                      this
                    , jQuery("#xAxis").val()        // 자르기를 시작할 x좌표
                    , jQuery("#yAxis").val()        // 자르기를 시작할 y좌표
                    , jQuery("#wLength").val()    // 잘라낸 이미지의 넓이
                    , jQuery("#hLength").val()    // 잘라낸 이미지의 높이
                    , 0                                         // 캔버스에 이미지를 배치할 x좌표
                    , 0                                         // 캔버스에 이미지를 배치할 y좌표
                    , jQuery("#wLength").val()    // 사용할 이미지의 넓이(이미지 스트레칭 또는 축소)
                    , jQuery("#hLength").val()    // 사용할 이미지의 높이(이미지 스트레칭 또는 축소)
                );


                // @breif 편집한 캔버스의 이미지를 화면에 출력한다.
                let dataURI = canvas.toDataURL("image/jpeg");
                jQuery("#editImg").attr("src", dataURI);
                
                // @breif 이미지의 크기는 자른 이미지와 동일하게 지정
                jQuery("#editImg").css("width", jQuery("#wLength").val());
                jQuery("#editImg").css("height", jQuery("#hLength").val());
            };


            jQuery("#cutBtn").css("display", "none");


            // @details JCROP을 종료한다.
            jcropApi.destroy();
    jcropApi = null;
        }
    }


    // @breif 이미지 업로드 함수
    function uploadImgFilePrinted() {


        // @details 업로드 파일 정보를 받아온다.
        let fileInfo = document.getElementById("uploadFile").files[0];
        let reader = new FileReader();


        reader.onload = function() {


            // @details 업로드 이미지 출력
            jQuery("#editImg").attr("src", reader.result);
            
            // @details 이미지 크기를 제목 영영과 같게 출력
            jQuery("#editImg").css("width", jQuery("h1").width());
            
            // @details 이미지 업로드 기능 제거, 추가 업로드 방지
            jQuery("#editImg").parent("a").removeAttr("onClick");
            
            // @details 편집버튼 노출
            jQuery("#editBtn").css("display", "inline");
            
            canvasDrawImage(function() {
             alert("이미지 업로드가 완료되었습니다.");
            });
        };


        if(fileInfo) {      
            // @details readAsDataURL을 통해 업로드한 파일의 URL을 읽어 들인다.
            reader.readAsDataURL(fileInfo);
        }
    }


    // @breif 캔버스 이미지 생성
    function canvasDrawImage(callback) {


        let prepImage = new Image();
        prepImage.src = jQuery("#editImg").attr("src");


        prepImage.onload = function() {


            // @details 캔버스 위에 이미지 그리기
            // jQuery("canvas") 와같은 명령은 사용할 수 없다.
            let canvas = document.querySelector("canvas");
            let canvasContext = canvas.getContext("2d");


            canvas.width = jQuery("#editImg").width();
            canvas.height = jQuery("#editImg").height();
            canvasContext.drawImage(this, 0, 0, jQuery("#editImg").width(), jQuery("#editImg").height());


            // @details 캔버스의 이미지
            let dataURI = canvas.toDataURL("image/jpeg");
            jQuery("#editImg").attr("src", dataURI);
            
            callback();
        };
    }
</script>
</head>
<body>
<input type="hidden" id="xAxis" value="0" placeholder="선택영여역의_x좌표"/>
<input type="hidden" id="yAxis" value="0" placeholder="선택영여역의_y좌표"/>
<input type="hidden" id="wLength" value="0" placeholder="선택영여역의_w넓이"/>
<input type="hidden" id="hLength" value="0" placeholder="선택영여역의_h높이"/>
<input type="file" id="uploadFile" onChange="uploadImgFilePrinted();" accept="image/*"/>
<div class="contents">
    <h1>이미지 자르기<span>샘플</span></h1>
    <div class="imgArea">
        <a href="javascript:;" onClick="jQuery('#uploadFile').click();">
            <img id="editImg" src="./user-anonymous.png"/>
        </a>
        <br/><br/>
        <input id="editBtn" type="button" onClick="imgCropDesignate();" value="편집"/>
        <input id="cutBtn" type="button" onClick="imgCropApply();" value="자르기"/>
    </div>
    <canvas></canvas>
    <div class="copyright" style="bottom:0;">
        <p>Producer © 사악미소</p>
    </div>
</div>
</body>
</html> 

 

 

 

 

# 출력결과

9943F44D5E793AA110

 

0
0
이 글을 페이스북으로 퍼가기 이 글을 트위터로 퍼가기 이 글을 카카오스토리로 퍼가기 이 글을 밴드로 퍼가기

HTML/CSS/기타

번호 제목 글쓴이 날짜 조회수
29 자주 사용하는 비주얼 스튜디오 코드(Visual Studio Code, VSC, vscode) 단축키 정리 관리자 09-14 5,382
28 div 2개 나란히 정렬하는 방법 관리자 09-09 4,944
27 HTML, CSS - 헤더컬럼 고정형 table 구성하기 관리자 09-06 4,499
26 Drag and Drop File Upload 관리자 09-03 3,082
25 rowspan으로 합친 table에서 룰오버 관리자 08-23 2,586
24 스마트에디터 입력 용량 체크 관리자 07-06 1,967
23 자바스크립트 정규표현식 모음 관리자 07-03 1,252
22 [Javascript] 쓰레드(웹 워커-Web worker)를 사용하는 방법 관리자 04-13 1,122
21 구글 차트 관리자 04-12 1,697
20 Camera API 관리자 04-07 852
19 전화번호 자동 정규식 처리 관리자 04-06 902
18 picocss 관리자 04-03 850
17 CSS 폰트 적용하기 관리자 03-15 752
16 JQuery html2canvas div 이미지 저장 (div 영역 이미지 캡쳐) 관리자 03-15 2,470
15 [#. CSS] 이미지 위에 텍스트, 글자 올리기 text on image 관리자 03-15 2,548
14 다음 지도 api 주소을 좌표 구하고 여러개 마커 제어하기 관리자 03-08 1,139
13 jquery upload 관리자 02-27 685
12 QR코드 활용에 관하여… 관리자 02-08 916
11 비밀번호 정규식 모음 관리자 11-21 830
10 JQuery 노드찾기 관리자 11-12 845