Pada sesi kali ini saya akan melanjutkan penjelasan tentang Cara Upload Dan Crop Gambar Dengan JQuery Part-2. Dan pada pejelasan di sini saya akan langsung lanjutkan dari sesi sebelumnya.

Berikut tahapan lanjutan nya:

  • Buatlah file dengan nama fungsi.js, letakan sejajar dengan file index.php, tuliskan kode seperti di bawah ini:
jQuery(document).ready(function(){
	/* Saat mengklik Ganti Foto Profil */
	jQuery('#change-profile-pic').on('click', function(e){
        jQuery('#profile_pic_modal').modal({show:true});
    });
	jQuery('#profile-pic').on('change', function()	{
		jQuery("#preview-profile-pic").html('');
		jQuery("#preview-profile-pic").html('Sedang mengupload....');
		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();

	});
	/* menangani fungsi saat mengklik tombol crop  */
	jQuery('#save_crop').on('click', function(e){
    e.preventDefault();
    params = {
            targetUrl: 'replace_image.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);
    });
    /* Fungsi untuk mendapatkan ukuran gambar */
    function getSizes(img, obj){
        var x_axis = obj.x1;
        var x2_axis = obj.x2;
        var y_axis = obj.y1;
        var y2_axis = obj.y2;
        var thumb_width = obj.width;
        var thumb_height = obj.height;
        if(thumb_width > 0) {
			jQuery('#hdn-x1-axis').val(x_axis);
			jQuery('#hdn-y1-axis').val(y_axis);
			jQuery('#hdn-x2-axis').val(x2_axis);
			jQuery('#hdn-y2-axis').val(y2_axis);
			jQuery('#hdn-thumb-width').val(thumb_width);
			jQuery('#hdn-thumb-height').val(thumb_height);
        } else {
            alert("Silakan pilih bagian yang dicrop..!");
		}
    }
    /* Fungsi untuk menyimpan gambar yang dicrop */
    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'],
									h1: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('src', response);
					jQuery("#preview-profile-pic").html('');
					jQuery("#profile-pic").val();
			},
			error: function (xhr, ajaxOptions, thrownError) {
				alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
			}
		});
    }
});
  • Buatlah satu buah file dengan nama replace_image.php dan letakan sejajar dengan file index.php, tuliskan kode seperti di bawah ini:
<?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 = 'img';
	$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='' src='".$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;
}
/* Fungsi untuk menyimpan foto profil */
function saveProfilePic($options){
	//Menangani update foto profil dengan Query update MySQL menggunakan array $options
}

/* Update gambar */
 function saveProfilePicTmp() {
	$post = isset($_POST) ? $_POST: array();
	$userId = isset($post['id']) ? intval($post['id']) : 0;
	$path ='\\img';
	$t_width = 300; // Lebar thumbnail maksimum
	$t_height = 300;    // Tinggi thumbnail maksimum
	if(isset($_POST['t']) and $_POST['t'] == "ajax") {
		extract($_POST);
		$imagePath = 'img/'.$_POST['image_name'];
		$ratio = ($t_width/$w1);
		$nw = ceil($w1 * $ratio);
		$nh = ceil($h1 * $ratio);
		$nimg = imagecreatetruecolor($nw,$nh);
		$im_src = imagecreatefromjpeg($imagePath);
		imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
		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;
}
?>
  • Terakhir, buatlah satu folder dengan nama img, dimana folder tersebut nantinya tempat untuk menyimpan gambar hasil crop.

Sampai di sini penjelasan saya mengenai cara upload dan crop gambar dengan jQuery, semoga bermanfaat.