ahmadajah03 Tue Jul 2020 2 years ago

Contoh Crop Image Sebelum di Upload pada Laravel

Hai kawan,

Dalam tutorial ini, saya akan mempelajari cara menggunakan crop image di laravel. Anda dapat dengan mudah dan mudah menggunakan crop image menggunakan cropper.js laravel

Cropper.js adalah plugin JavaScript/jQuery yang mudah digunakan untuk crop image dengan dukungan pratinjau langsung dan rasio aspek kustom. Plugin ini menyediakan fitur pemindahan, pembesaran, rotasi, responsif sepenuhnya, dan ramah seluler.

Plugin ini menampilkan layer grid resizable pada gambar yang diberikan memungkinkan untuk mengubah ukuran visual dan memotong gambar.

Saya akan menggunakan tampilan model sebagai contoh. tampilan model untuk mengunggah gambar dan memotong pratinjau gambar. Ikuti contoh langkah di bawah ini.

 

Langkah 1: Buat Route

Pada langkah pertama ini, Anda akan membuat route dalam file web.php.

route/web.php

Route::get('image-cropper','ImageCropperController@index');
Route::post('image-cropper/upload','ImageCropperController@upload');

Langkah 2: Buat Controller

Pada langkah ini, Anda akan membuat controller di ImageCropperController.php.

app/Http/Controller/ImageCropperController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageCropperController extends Controller
{

    public function index()
    {
        return view('cropper');
    }

    public function upload(Request $request)
    {
        $folderPath = public_path('upload/');

        $image_parts = explode(";base64,", $request->image);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $file = $folderPath . uniqid() . '.png';

        file_put_contents($file, $image_base64);

        return response()->json(['success'=>'success']);
    }
}

Langkah 3: Create File View

Pada langkah, Anda akan membuat file cropper.blade.php di folder views.

resources/views/cropper.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Crop Image Before Upload using Cropper JS</title>
    <meta name="_token" content="{{ csrf_token() }}">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" integrity="sha256-jKV9n9bkk/CTP8zbtEtnKaKf+ehRovOYeKoyfthwbC8=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js" integrity="sha256-CgvH7sz3tHhkiVKh05kSUgG97YtzYNnWt6OXcmYzqHY=" crossorigin="anonymous"></script>
</head>
<style type="text/css">
img {
  display: block;
  max-width: 100%;
}
.preview {
  overflow: hidden;
  width: 160px; 
  height: 160px;
  margin: 10px;
  border: 1px solid red;
}
.modal-lg{
  max-width: 1000px !important;
}
</style>
<body>
<div class="container">
  <h1>Laravel Crop Image Before Upload using Cropper JS - Medikre.com</h1>
    <input type="file" name="image" class="image">
</div>

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Laravel Crop Image Before Upload using Cropper JS - NiceSnippets.com</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="img-container">
            <div class="row">
                <div class="col-md-8">
                    <img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
                </div>
                <div class="col-md-4">
                    <div class="preview"></div>
                </div>
            </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="crop">Crop</button>
      </div>
    </div>
  </div>
</div>

</div>
</div>
<script>

var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
  
$("body").on("change", ".image", function(e){
    var files = e.target.files;
    var done = function (url) {
      image.src = url;
      $modal.modal('show');
    };
    var reader;
    var file;
    var url;

    if (files && files.length > 0) {
      file = files[0];

      if (URL) {
        done(URL.createObjectURL(file));
      } else if (FileReader) {
        reader = new FileReader();
        reader.onload = function (e) {
          done(reader.result);
        };
        reader.readAsDataURL(file);
      }
    }
});

$modal.on('shown.bs.modal', function () {
    cropper = new Cropper(image, {
   aspectRatio: 1,
   viewMode: 3,
   preview: '.preview'
    });
}).on('hidden.bs.modal', function () {
   cropper.destroy();
   cropper = null;
});

$("#crop").click(function(){
    canvas = cropper.getCroppedCanvas({
     width: 160,
     height: 160,
      });

    canvas.toBlob(function(blob) {
        url = URL.createObjectURL(blob);
        var reader = new FileReader();
         reader.readAsDataURL(blob); 
         reader.onloadend = function() {
            var base64data = reader.result; 

            $.ajax({
                type: "POST",
                dataType: "json",
                url: "image-cropper/upload",
                data: {'_token': $('meta[name="_token"]').attr('content'), 'image': base64data},
                success: function(data){
                    $modal.modal('hide');
                    alert("success upload image");
                }
              });
         }
    });
})

</script>
</body>
</html> 

Langkah 5: Buat Folder

pada langkah ini, Anda akan membuat folder public/upload. Dalam folder ini masukkan untuk croping image.

Itu akan membantumu.....

 

crop image laravel laravel 7 laravel upload image laravel