Chào các bạn, hôm nay mình sẽ hướng dẫn các bạn cách upload ảnh lên server đồng thời sẽ resize lại kích thước của bức ảnh bằng PHP
Demo ảnh
Cấu trúc
Bài viết này thao tác trên 3 thư mục là js
, include
, uploads
và các file bao gồm
-
includes
- — getExtension.php
- — compressImage.php
-
js
- — jquery.min.js
- — jquery.form.js
- uploads
- index.php
- ajaximageupload.php
- db.php
Code
Database
Chúng ta khởi tạo một bảng cơ sở dữ liệu có các trường sau đây:
1 2 3 4 5 6 7 | CREATE TABLE `users` ( `uid` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email` varchar(255) UNIQUE KEY, `profile_image` varchar(200) ) |
File kết nối db.php
1 2 3 4 5 6 7 | <?php define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'username'); define('DB_PASSWORD', 'password'); define('DB_DATABASE', 'database'); $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); ?> |
index.php
Trong đó, file index.php sẽ có code sau
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php include('db.php'); session_start(); $session_id='1'; // User login session value ?> <div id='preview'> </div> <form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'> Upload image: <div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div> <div id='imageloadbutton'> <input type="file" name="photoimg" id="photoimg" /> </div> </form> |
Chúng ta áp dụng đoạn code sau để làm ẩn hiện các button bằng việt áp dụng các id #imageloadstatus
và #imageloadbutton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <script type="text/javascript" src="http://ajax.googleapis.com/ ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.form.js"></script> <script type="text/javascript"> $(document).ready(function() { $('body').on('change','#photoimg', function() { var A=$("#imageloadstatus"); var B=$("#imageloadbutton"); $("#imageform").ajaxForm({target: '#preview', beforeSubmit:function(){ A.show(); B.hide(); }, success:function(){ A.hide(); B.show(); }, error:function(){ A.hide(); B.show(); } }).submit(); }); }); </script> |
Ajaximage.php
File này chứa các đoạn code ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <?php include('db.php'); session_start(); $session_id='1'; // User session id $path = "uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { include_once 'includes/getExtension.php'; $imagename = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($imagename)) { $ext = strtolower(getExtension($imagename)); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) // Image size max 1 MB { $actual_image_name = time().$session_id.".".$ext; $uploadedfile = $_FILES['photoimg']['tmp_name']; //Re-sizing image. include 'includes/compressImage.php'; $widthArray = array(200,100,50); //You can change dimension here. foreach($widthArray as $newwidth) { $filename=compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth); echo "<img src='".$filename."' class='img'/>"; } //Original Image if(move_uploaded_file($uploadedfile, $path.$actual_image_name)) { //Insert upload image files names into user_uploads table mysqli_query($db,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id';"); echo "<img src='uploads/".$actual_image_name."' class='preview'>"; } else echo "failed"; } else echo "Image file size max 1 MB"; } else echo "Invalid file format.."; } else echo "Please select image..!"; exit; } ?> |
CompressImage.php
File dùng để resize lại ảnh khi upload lên
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php function compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth) { if($ext=="jpg" || $ext=="jpeg" ) { $src = imagecreatefromjpeg($uploadedfile); } else if($ext=="png") { $src = imagecreatefrompng($uploadedfile); } else if($ext=="gif") { $src = imagecreatefromgif($uploadedfile); } else { $src = imagecreatefrombmp($uploadedfile); } list($width,$height)=getimagesize($uploadedfile); $newheight=($height/$width)*$newwidth; $tmp=imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); $filename = $path.$newwidth.'_'.$actual_image_name; //PixelSize_TimeStamp.jpg imagejpeg($tmp,$filename,100); imagedestroy($tmp); return $filename; } ?> |
Nội dung file getExtension.php
1 2 3 4 5 6 7 8 9 10 11 | function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } |
Download code
[postbytag bytag=”upload-anh”]Upload ảnh bằng ajax[/postbytag]
(9Lessions)
You must log in to post a comment.