まずはよくあるbootstrapのmodalと画像ファイルをアップするボタンを用意。
form.html
<form enctype="multipart/form-data" method="post">
<input class="img btn btn-primary btn-lg"
type="file"
accept="image/*" >
</form>
modal.html
<div class="modal fade" id="modal-img" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
<h4 class="modal-title">タイトル</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button id="get-button" type="button" class="btn btn-default" data-dismiss="modal">OK</button>
<button id="not-button" type="button" class="btn btn-default" data-dismiss="modal">閉じる</button>
</div>
</div>
</div>
</div>
今回はjQueryの使用。
そして、cropperでトリミング内容を取得を行うので下記を追加を行う。
<!-- CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/1.0.0/cropper.min.css" rel="stylesheet" type="text/css" media="all"/>
<!-- JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/1.0.0/cropper.min.js"></script>
まずはファイルを選択したときにmodalを表示を行い、画像のトリミング加工を行うものを表示。
jQuery.html
<script type="text/javascript">
$('input[type=file]').change(function() {
// ファイルの取得
var file = $(this).prop('files')[0];
// modal表示
$('#modal-img').modal();
// 画像表示
var reader = new FileReader();
reader.onload = function() {
var img_src = $('<img id="cropper">').attr('src', reader.result);
$('.modal-body').html(img_src);
$('.modal-body img').cropper({aspectRatio: 4 / 4});
// ワイド画面 ⇒ 16 / 9
}
reader.readAsDataURL(file);
});
</script>
元画像とトリミング内容を送る
jQuery.html
<script type="text/javascript">
$('#get-button').on('click', function() {
var img_file = $('#cropper').attr('src');
var data = $('.modal-body img').cropper('getData');
var image = {
width: Math.round(data.width),
height: Math.round(data.height),
x: Math.round(data.x),
y: Math.round(data.y),
};
$.ajax({
type: "POST",
url: "URL",
data: { img_file, image },
success:function(res) {
console.log(res);
}
});
});
</script>
画像加工はまだ作ってないのでできたら追記します。