ㅇㅅㅇ

cropper.js를 사용해 업로드한 이미지 자르기 본문

프로그래밍/JQUERY

cropper.js를 사용해 업로드한 이미지 자르기

소 아 2020. 9. 3. 00:00

! 티스토리 블로그가 아직 익숙하지 않은 블로거라 여러모로 어색할 수 있습니다ㅜㅅ

! 이유없는 비난외의 잘못된 부분에 대한 조언이나 후기 등의 덧글은 환영합니다.ㅎ

 

업무에 실제로 사용한 소스다.

업로드한 사진에서 얼굴만 잘라 쓸 수 있도록 하는 플러그인이 필요해 찾아보게 되었다.

사진업로드 -> 업로드한 사진에 cropper.js 실행 -> 업로드 버튼 클릭 시 크롭된 사진이 보이게끔 했다.

 

플러그인은 제목에 썼지만 cropper.js를 사용했다.

 

Cropper.js

 

fengyuanchen.github.io

(올린 링크로)1.5.7버전으로 들어가면 몇 가지 예시를 볼 수 있고, 작성일 기준, 현재까지 4.1.0버전까지 나온거 같다.

cropper.js에서 지원하는 옵션에 따라 낮은버전을 사용하면 작동이 안되니 작업 전 확인하고 작업하자

(낮은 버전을 사용하다 정상작동이 안 되어 삽질했던 1인....)

 

1. 필요 플러그인 소스

작업한 소스의 cropper.js는 작성일 기준, 최신버전인 4.1.0을 다운받아 작업했다.

<!-- css -->
<link rel="stylesheet" type="text/css" href="https://fengyuanchen.github.io/cropperjs/css/cropper.css">

<!-- js -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://fengyuanchen.github.io/cropper/js/cropper.js"></script>

 

2-1. html

<div class="photo_box">
  <div class="upload_btn">
    <div class="upload">
    	<input type="file" name="photoBtn" accept="image/jpeg, image/png" capture="camera" id="photoBtn"><label for="photoBtn">사진 첨부하기</label>
    </div>
  	<a href="javascript:void(0);" id="resetPhoto">다시 올리기</a>
  </div>
  <div class="photo_them">
    <div class="them_img">
    	<img id="image" src="">
    </div>
  </div>
  <a href="javascript:void(0);" id="complete">업로드</a>
</div>

 

2-2. css(적당히 보는데 문제 없는 정도로만...)

.photo_box{margin:0 auto ;max-width:500px;} 
.upload_btn{overflow:hidden;width:100%;}
.upload_btn #photoBtn{display:none;}
.upload_btn .upload, .upload_btn a{float:left;width:calc(50% - 10px);text-align:center;text-decoration: none;color:#fff;padding:15px 0;}
.upload_btn .upload{background-color:steelblue;} 
.upload_btn a{margin-left:20px; background:#ccc;}
.photo_them{position:relative;margin-top:20px;width:100%;height:250px;background:#eee;}
.them_img, .result_box{position:absolute;top:0;left:0;width:100%;height:100%;}
.result_box{background:#fff;}
.them_img img, .result_box img{display:block;margin:0 auto;height:100%;}
#complete{display:block;margin-top:20px;padding:15px 0;width:100%;text-align:center;color:#fff;text-decoration: none;background-color: steelblue;}

css로 input[type="file"]은 숨기고, label로 버튼모양을 적당히 만들었다.

필요에 의해 사진 나오는 공간에 position을 썼는데 굳이 이렇게 안해도 상관은 없다.

 

작성한 대로 html + css하면 모양은 이렇다.

 

2-3. js

$(function(){
	var cropper;
    // 사진 업로드 버튼
    $('#photoBtn').on('change', function(){
        $('.them_img').empty().append('<img id="image" src="">');
        var image = $('#image');
        var imgFile = $('#photoBtn').val();
        var fileForm = /(.*?)\.(jpg|jpeg|png)$/;
		
        // 이미지가 확장자 확인 후 노출
        if(imgFile.match(fileForm)) {
        	var reader = new FileReader(); 
        	reader.onload = function(event) { 
        		image.attr("src", event.target.result);
        		cropper = image.cropper( {
        			dragMode: 'move',
        			viewMode:1,
        			aspectRatio: 1,
        			autoCropArea:0.9,
        			minCropBoxWidth:200,
       				restore: false,
                    guides: false,
                    center: false,
                    highlight: false,
                    cropBoxMovable: false,
                    cropBoxResizable: false,
                    toggleDragModeOnDblclick: false
                });
            }; 
        	reader.readAsDataURL(event.target.files[0]);
        } else{
        	alert("이미지 파일(jpg, png형식의 파일)만 올려주세요");
        	$('#photoBtn').focus();
        	return; 
        }
	});
    // 사진 다시 올리기 버튼
    $('#resetPhoto').on('click', function(){
        if($('input[type="file"]').val() != ""){
        	$('#photoBtn').val('');
        	$('.them_img img').attr('src','').remove();
        	$('.btn_wrap a:last-child').removeClass('bg1');
        	$('input[type="file"]').click();
        }else{
        	//alert('업로드된 사진이 없습니다.');
        }
    });
    // 업로드 버튼
    $('#complete').on('click', function(){
    	$('.them_img').append('<div class="result_box"><img id="result" src=""></div>');
    	var image = $('#image');
    	var result = $('#result');
    	var canvas;
    	if($('input[type="file"]').val() != ""){
    	canvas = image.cropper('getCroppedCanvas',{
    		width:200,
    		height:200
    	});
    	result.attr('src',canvas.toDataURL("image/jpg"));

    	canvas.toBlob(function (blob) {
    		var formData = new FormData();

    		$.ajax('보낼곳 url', {
           		method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function () {
                	alert('업로드 성공');
                },
                error: function () {
                	alert('업로드 실패');
                	$('.result_box').remove()
                },
    		});
    	})
      }else{
          alert('사진을 업로드 해주세요');
          $('input[type="file"]').focus();
          return;
      }
    });
});

cropper({}); 에 들어간 옵션들은 해당 플러그인의 깃에 들어가면 확인할 수 있다. 외부에 옵션으로 크롭하는 사각형 크기를 바꿀 수 있고 버튼 과 기능을 추가해 사진 회전이나 확대 등도 가능하다.

 

이미지 업로드 후 cropper 구동 화면 / 업로드 버튼 누르면 나오는 화면

나는 이미지 업로드 후 cropper이 실행되는데 크롭하는 사각형의 모양과 크기는 고정하고, 업로드한 이미지가 확대, 축소, 음직일 수 있도록 했다. 업로드 버튼을 누르면 크롭된 이미지를 확인해 볼 수 있다. ajax부분은 백엔드 연결시 문제가 없었던 걸로 기억하니 아마 될 것이다.

 

! 티스토리 블로그가 아직 익숙하지 않은 블로거라 여러모로 어색할 수 있습니다ㅜㅅ

! 이유없는 비난외의 잘못된 부분에 대한 조언이나 후기 등의 덧글은 환영합니다.ㅎ

Comments