Ditutorial kali ini Writecode masih akan membahas Upload Crop image PHP Mysql menggunakan Jquery, sebelum memulai masuk ke koding-koding apa saja yang harus dipersiapkan Karena disini Writecode menggunakan Jquery silakan anda download Jquery di link berikut AKU DISINI name file Jquery yang harus anda download (jquery.imgareaselect.js,jquery.form.js) bila sudah di download silakan anda masukan ke dalam folder latihan anda untuk susunan directorynya seperti dibawah ini :
Direktory
- assets
- images-tmp
File PHP
- index.php
- header.php
- footer.php
- change_pic.php
- db_connect.php
- functions.js
Step 1 silakan anda buat tabel didalam database latihan anda seperti dibawah ini :
Baca Juga : Upload crop image php jquery
Baca Juga : Upload crop image php jquery
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(255) DEFAULT NULL,
`pass` varchar(100) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`profile_photo` varchar(200) DEFAULT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`user`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB
Step 2 buat file koneksi database db_connect.php untuk script kode seperti dibawah ini :
<?php /* Database connection start */ $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "name database"; $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error()); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
Step 3 buat file index.php untuk script kode seperti dibawah ini :
<?php
include_once("db_connect.php");
include_once('header.php');
?>
<div role="navigation" class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="#" class="navbar-brand">IMAGE UPLOAD CROP 2 PHP MYSQL MODAL</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="http://www.phpzag.com">Home</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" style="min-height:500px;">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h2 style="text-transform: uppercase;">Image Upload and Image Crop in Modal with PHP and jQuery</h2>
</div>
<div class="panel-body text-center">
<img class="img-circle" id="profile_picture" height="128" data-src="default.jpg" data-holder-rendered="true" style="width: 140px; height: 140px;" src="default.jpg"/>
<br><br>
<a type="button" class="btn btn-primary" id="change-profile-pic">Change Profile Picture</a>
</div>
<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">×</button>
<h3>Change Profile Picture</h3>
</div>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="change_pic.php">
<strong>Upload Image:</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">Close</button>
<button type="button" id="save_crop" class="btn btn-primary">Crop & Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include_once('footer.php');?>
Step 4 buat file header.php script kode seperti dibawah ini :
Baca Juga : Ajax add & delete a Record with jQuery Fade In/Fade Out
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
<title>Dome of Image Upload and Image Crop in Modal with PHP and jQuery</title>
<script src="assets/jquery.imgareaselect.js" type="text/javascript"></script>
<script src="assets/jquery.form.js"></script>
<link rel="stylesheet" href="dist_files/imgareaselect.css">
<script src="functions.js"></script>
<style type="text/css">
img {
width: 100%;
height: auto;
margin-top: 20px;
}
</style>
</head>
<body>
Step 5 script kode footer.php seperti dibawah ini :
<div class="insert-post-ads1" style="margin-top:20px;">
</div>
</div>
</body>
</html>
Step 6 Buat file php dengan nama file change_pic.php didalama folder latihan anda untuk script kode seperti dibawah :
<?php /* Get post details */ $post = isset($_POST) ? $_POST: array(); switch($post['action']) { case 'save' : saveProfilePic(); saveProfilePicTmp(); break; default: changeProfilePic(); } /* Function to change profile picture */ function changeProfilePic() { $post = isset($_POST) ? $_POST: array(); $max_width = "500"; $userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0; $path = 'images/tmp'; $valid_formats = array("jpg", "png", "gif", "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); //Scale the image if it is greater than the width set above if ($width > $max_width){ $scale = $max_width/$width; $uploaded = resizeImage($filePath,$width,$height,$scale, $ext); } else { $scale = 1; $uploaded = resizeImage($filePath,$width,$height,$scale, $ext); } echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".$filePath.'?'.time()."' class='preview'/>"; } else echo "failed"; } else echo "Image file size max 1 MB"; } else echo "Invalid file format.."; } else echo "Please select image..!"; exit; } /* Function to handle save profile pic */ function saveProfilePic(){ include_once("db_connect.php"); $post = isset($_POST) ? $_POST: array(); //Handle profile picture update with MySQL update Query using $options array if($post['id']){ $sql_query = "SELECT * FROM users WHERE uid = '".mysqli_escape_string($conn, $post['id'])."'"; $resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn)); if(mysqli_num_rows($resultset)) { $sql_update = "UPDATE users set profile_photo='".mysqli_escape_string($conn,$post['image_name'])."' WHERE uid = '".mysqli_escape_string($conn, $post['id'])."'"; mysqli_query($conn, $sql_update) or die("database error:". mysqli_error($conn)); } } } /* Function to update image */ function saveProfilePicTmp() { $post = isset($_POST) ? $_POST: array(); $userId = isset($post['id']) ? intval($post['id']) : 0; $path ='\\images\tmp'; $t_width = 300; // Maximum thumbnail width $t_height = 300; // Maximum thumbnail height if(isset($_POST['t']) and $_POST['t'] == "ajax") { extract($_POST); $imagePath = 'images/tmp/'.$_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); } /* Function to resize image */ function resizeImage($image,$width,$height,$scale, $ext) { $newImageWidth = ceil($width * $scale); $newImageHeight = ceil($height * $scale); $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); switch ($ext) { case 'jpg': case 'jpeg': $source = imagecreatefromjpeg($image); break; case 'gif': $source = imagecreatefromgif($image); break; case 'png': $source = imagecreatefrompng($image); break; default: $source = false; break; } imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height); imagejpeg($newImage,$image,90); chmod($image, 0777); return $image; } /* Function to get image height. */ function getHeight($image) { $sizes = getimagesize($image); $height = $sizes[1]; return $height; } /* Function to get image width */ function getWidth($image) { $sizes = getimagesize($image); $width = $sizes[0]; return $width; }
Step 7 lalu anda buat file js dengan nama function.js untuk script kode seperti dibawah ini :
Baca Juga : Cara Mengirim Email Massal di PHP menggunakan PHPMailer dengan Ajax JQuery
jQuery(document).ready(function(){
/* When click on change profile pic */
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('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();
});
/* handle functionality when click crop button */
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);
});
/* Function to get images size */
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("Please select portion..!");
}
}
/* Function to save crop images */
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);
}
});
}
});
Step 8 untuk folder image seperti dibawah ini :
$path = 'images/tmp';
Silakan anda praktekan step by step potongan script diatas bila anda memngikuti dengan benar koding diatas tidak ada masalah, support PHP 5 keatas system database menggunakan Mysqli, silakan kirim komentar dibawah bila ada ada masalah dengan kodingnya.
Posting Komentar
Posting Komentar