Cara menggunakan crop image php jquery

Langkah 3: Sekarang kita akan membuat box modal di index.php untuk meng-upload dan crop gambar.

<div id="profile_pic_modal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Ganti Foto Profil</h3> </div> <div class="modal-body"> <form id="cropimage" method="post" enctype="multipart/form-data" action="change_pic.php"> <strong>Upload gambar:</strong> <br><br> <input type="file" name="profile-pic" id="profile-pic" /> <input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" /> <input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" /> <input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" /> <input type="hidden" name="hdn-x2-axis" value="" id="hdn-x2-axis" /> <input type="hidden" name="hdn-y2-axis" value="" id="hdn-y2-axis" /> <input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" /> <input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" /> <input type="hidden" name="action" value="" id="action" /> <input type="hidden" name="image_name" value="" id="image_name" /> <div id='preview-profile-pic'></div> <div id="thumbs" style="padding:5px; width:600p"></div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button> <button type="button" id="save_crop" class="btn btn-primary">Crop &amp; Simpan</button> </div> </div> </div> </div>

Langkah 4: Sekarang akan menampilkan box modal menggunakan jQuery saat mengklik tombol Ganti Foto Profil.

jQuery('#change-profile-pic').on('click', function(e){ jQuery('#profile_pic_modal').modal({show:true}); });

Langkah 5: Sekarang kita akan menampilkan gambar untuk proses cropping pada box modal bootstrap dan juga menangani submit formulir menggunakan Plugin form jQuery.

jQuery('#profile-pic').on('change', function() { jQuery("#preview-profile-pic").html(''); jQuery("#preview-profile-pic").html('Uploading....'); jQuery("#cropimage").ajaxForm( { target: '#preview-profile-pic', success: function() { jQuery('img#photo').imgAreaSelect({ aspectRatio: '1:1', onSelectEnd: getSizes, }); jQuery('#image_name').val(jQuery('#photo').attr('file-name')); } }).submit(); });

Langkah 6: Sekarang kita akan menangani crop gambar dan memanggil ajax method saveCropImage()  untuk menyimpan gambar pada penyimpanan hard disk saat mengklik tombol Crop & Simpan.

jQuery('#save_crop').on('click', function(e){ e.preventDefault(); params = { targetUrl: 'change_pic.php?action=save', action: 'save', x_axis: jQuery('#hdn-x1-axis').val(), y_axis : jQuery('#hdn-y1-axis').val(), x2_axis: jQuery('#hdn-x2-axis').val(), y2_axis : jQuery('#hdn-y2-axis').val(), thumb_width : jQuery('#hdn-thumb-width').val(), thumb_height:jQuery('#hdn-thumb-height').val() }; saveCropImage(params); });

Langkah 7: fungsi JavaScript saveCropImage() untuk menyimpan gambar yang di-crop.

function saveCropImage(params) { jQuery.ajax({ url: params['targetUrl'], cache: false, dataType: "html", data: { action: params['action'], id: jQuery('#hdn-profile-id').val(), t: 'ajax', w1:params['thumb_width'], x1:params['x_axis'], h2:params['thumb_height'], y1:params['y_axis'], x2:params['x2_axis'], y2:params['y2_axis'], image_name :jQuery('#image_name').val() }, type: 'Post', success: function (response) { jQuery('#profile_pic_modal').modal('hide'); jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none'); jQuery("#profile_picture").attr('srx', response); jQuery("#preview-profile-pic").html(''); jQuery("#profile-pic").val(); }, error: function (xhr, ajaxOptions, thrownError) { alert('status Code:' + xhr.status + 'Error Message :' + thrownError); } }); }

Langkah 8: Sekarang, meng-upload foto profil di server-side untuk meng-upload gambar/mengubah gambar pada server dan juga menyimpan gambar yang diubah menjadi tabel database MySQL dalam file ganti_foto.php.

<?php /* Mendapatkan rincian POST */ $post = isset($_POST) ? $_POST: array(); switch($post['action']) { case 'save' : saveProfilePicTmp(); break; default: changeProfilePic(); } /* Fungsi untuk mengubah foto profil */ function changeProfilePic() { $post = isset($_POST) ? $_POST: array(); $max_width = "500"; $userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0; $path = 'gambar/tmp'; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); $name = $_FILES['profile-pic']['name']; $size = $_FILES['profile-pic']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) { $actual_image_name = 'avatar' .'_'.$userId .'.'.$ext; $filePath = $path .'/'.$actual_image_name; $tmp = $_FILES['profile-pic']['tmp_name']; if(move_uploaded_file($tmp, $filePath)) { $width = getWidth($filePath); $height = getHeight($filePath); //Menskalakan gambar jika lebih besar dari lebar yang ditentukan di atas if ($width > $max_width){ $scale = $max_width/$width; $uploaded = resizeImage($filePath,$width,$height,$scale); } else { $scale = 1; $uploaded = resizeImage($filePath,$width,$height,$scale); } $res = saveProfilePic(array( 'userId' => isset($userId) ? intval($userId) : 0, 'avatar' => isset($actual_image_name) ? $actual_image_name : '', )); echo "<img id='photo' file-name='".$actual_image_name."' class='' srx='".$filePath.'?'.time()."' class='preview'/>"; } else echo "gagal"; } else echo "Ukuran file gambar maksimal 1 MB"; } else echo "Format file tidak valid.."; } else echo "Silakan pilih gambar..!"; exit; } /* Update gambar */ function saveProfilePicTmp() { $post = isset($_POST) ? $_POST: array(); $userId = isset($post['id']) ? intval($post['id']) : 0; $path ='\\images\tmp'; $t_width = 300; // Lebar thumbnail maksimum $t_height = 300; // Tinggi thumbnail maksimum if(isset($_POST['t']) and $_POST['t'] == "ajax") { extract($_POST); $imagePath = 'gambar/tmp/'.$_POST['image_name']; $ratio = ($t_width/$w1); $nw = ceil($w1 * $ratio); $nh = ceil($h2 * $ratio); $nimg = imagecreatetruecolor($nw,$nh); $im_srx = imagecreatefromjpeg($imagePath); imagecopyresampled($nimg,$im_srx,0,0,$x1,$y1,$nw,$nh,$w1,$h2); imagejpeg($nimg,$imagePath,90); } echo $imagePath.'?'.time();; exit(0); } /* Fungsi untuk mengubah ukuran gambar */ function resizeImage($image,$width,$height,$scale) { $newImageWidth = ceil($width * $scale); $newImageHeight = ceil($height * $scale); $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); $source = imagecreatefromjpeg($image); imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height); imagejpeg($newImage,$image,90); chmod($image, 0777); return $image; } /* Fungsi untuk mendapatkan tinggi gambar */ function getHeight($image) { $sizes = getimagesize($image); $height = $sizes[1]; return $height; } /* Fungsi untuk mendapatkan lebar gambar. */ function getWidth($image) { $sizes = getimagesize($image); $width = $sizes[0]; return $width; } ?>

Langkah 9: Sekarang terakhir, fungsi untuk menyimpan/update path gambar yang diubah ke dalam database MySQL dalam fungsi saveProfilePic().

function saveProfilePic($options){ //Menangani update foto profil dengan Query update MySQL menggunakan array $options }

Itu saja gan, ini adalah cara Upload dan Crop gambar dengan PHP dan jQuery. Kamu dapat mengembangkan kode tersebut lebih lanjut sesuai kebutuhanmu. Dan jangan ragu untuk vberkomentar.

  • Download Source Code
  • Lihat Demo

Postingan terbaru

LIHAT SEMUA