Upload Image Resize in PHP

Hôm này mình viết một bài chia sẻ với mọi người về upload image lên và resize nó thành nhiều tấm hình, để sử dụng cho mục đích hiện thị ngoài website
Đầu tiên ta sẽ tạo một giao diện để upload image thôi

Github : Upload Image Resize in PHP

+ Tạo tập tin index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="upload-image.php" method="post"  enctype="multipart/form-data">
            <label className="text-white text-sm">Choose file image : </label>
            <input type="file" name="UrlImage" />
            <button className='bg-green-600 text-white text-sm p-1 rounded-sm' type="submit">Upload file</button>
    </form>
</body>
</html

Trong đoạn code trên ta tạo một form để chọn file hình, các bạn nhớ thêm  enctype="multipart/form-data" này vào thẻ form nhé, không thôi sẽ không upload được hình ảnh
Ta có tạo một biến name chổ thẻ <input type="file" name="UrlImage" /> , mục đích dùng để $_FILES['UrlImage'] để nhận được thông tin của file mà ta upload lên 

+ Tiếp tục tạo file upload-image.php hứng giá trị của form upload thôi nào ::) 

 

header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
require_once './resize-image.php';
if(isset($_FILES['UrlImage'])){

    $dirname = __DIR__."/uploads/";
    $size320x200 = $dirname."size320x200";
    $size420x300 = $dirname."size420x300";

    $errors = array();
    $name = $_FILES['UrlImage']['name'];
    $type = $_FILES['UrlImage']['type'];
    $size = $_FILES['UrlImage']['size'];
    $tmp_name = $_FILES['UrlImage']['tmp_name'];
    $maxsize    = 2097152;
    $array_type = array("image/jpeg","image/png","image/jpg","image/gif");
    if(($size >= $maxsize) || ($size == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($type, $array_type)) && (!empty($type))) {
        $errors[] = 'Invalid file type. JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {

        if (!file_exists($dirname)) {
            mkdir($dirname, 0777);
        }
        /**Resize */
        if (!file_exists($size320x200)) {
            mkdir($size320x200, 0777);
        }
        if (!file_exists($size420x300)) {
            mkdir($size420x300, 0777);
        }
        $target_file = $dirname . basename($name);
        move_uploaded_file($tmp_name,  $target_file);
        //resize320x200
        ImageResize(320,200,$size320x200,$target_file,$type,$name);
         //resize320x200
        ImageResize(420,300,$size420x300,$target_file,$type,$name);
    
        echo json_encode(array("success"=>1,"message"=>"Upload successfuly!","data"=>"ok"));
    } else {
        echo json_encode(array("success"=>-1,"message"=>json_encode($errors)));
    }
}
else{
    echo json_encode(array("success"=>0));
}

Đoạn code bên trên mình có cung cấp thêm các headers để các bạn nào muốn request API để upload image thì tránh bị "Cors" 

header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

Oh, bạn sẽ thấy mình có gọi file require_once './resize-image.php' file này dùng để resize image, tí nửa mình nói sơ qua nó sau
Mình kiểm tra sự tồn tại của $_FILES['UrlImage'] , nếu nó ok thì lấy các giá trị trong nó thôi

 $dirname = __DIR__."/uploads/";
    //tạo thư mục con size320x200
    $size320x200 = $dirname."size320x200";
    //tạo thư mục con size420x300
    $size420x300 = $dirname."size420x300";
    $errors = array();
    $name = $_FILES['UrlImage']['name'];
    $type = $_FILES['UrlImage']['type'];
    $size = $_FILES['UrlImage']['size'];
    $tmp_name = $_FILES['UrlImage']['tmp_name'];

Kiểm tra type của file ta upload lên đúng với yêu câu không và size mà ta cần giớ hạn

 $maxsize    = 2097152;
    $array_type = array("image/jpeg","image/png","image/jpg","image/gif");
    if(($size >= $maxsize) || ($size == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($type, $array_type)) && (!empty($type))) {
        $errors[] = 'Invalid file type. JPG, GIF and PNG types are accepted.';
    }

Nếu mọi thứ không có lỗi gì cả, thì ta hãy kiểm tra folder có tồn tại chưa, nếu folder chưa có thì ta hãy tạo nó , rồi di chuyển file image đến từng thư mục:

 if (!file_exists($dirname)) {
            mkdir($dirname, 0777);
        }
        /**Resize */
        if (!file_exists($size320x200)) {
            mkdir($size320x200, 0777);
        }
        if (!file_exists($size420x300)) {
            mkdir($size420x300, 0777);
        }

        $target_file = $dirname . basename($name);
        move_uploaded_file($tmp_name,  $target_file);

        //resize320x200 call function ImageResize(...)
        ImageResize(320,200,$size320x200,$target_file,$type,$name);

         //resize320x200 call function ImageResize(...)
        ImageResize(420,300,$size420x300,$target_file,$type,$name);

Bạn sẽ nhìn thấy đoạn code trên mình có gọi function ImageResize($w, $h, $path_file,$tmp_name,$type,$name,$crop=FALSE)
Tạo file resize-image.php và copy đoạn mã dưới đây vào : 

function ImageResize($w, $h, $path_file,$tmp_name,$type,$name,$crop=FALSE)
{
     /* Get original file size */
   
     list($width, $height) = getimagesize($tmp_name);

     $r = $width / $height;
     if ($crop) {
         if ($width > $height) {
             $width = ceil($width-($width*abs($r-$w/$h)));
         } else {
             $height = ceil($height-($height*abs($r-$w/$h)));
         }
         $newwidth = $w;
         $newheight = $h;
     } else {
         if ($w/$h > $r) {
             $newwidth = $h*$r;
             $newheight = $h;
         } else {
             $newheight = $w/$r;
             $newwidth = $w;
         }
     }
 
     $path = $path_file."/".$name;
     /* Save image */
     if($type=='image/jpeg')
     {
        /* Get binary data from image */
        $imgString = file_get_contents($tmp_name);
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($tmp, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg($tmp, $path, 100);
         
     }
     else if($type=='image/png')
     {
         $image = imagecreatefrompng($tmp_name);
         $tmp = imagecreatetruecolor($newwidth, $newheight);
         imagealphablending($tmp, false);
         imagesavealpha($tmp, true);
         imagecopyresampled($tmp, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
         imagepng($tmp, $path, 0);
     }
     else if($type=='image/gif')
     {
         $image = imagecreatefromgif($tmp_name);

         $tmp = imagecreatetruecolor($newwidth, $newheight);
         $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
         imagefill($tmp, 0, 0, $transparent);
         imagealphablending($tmp, true); 

         imagecopyresampled($tmp, $image,0,0,0,0,$newwidth,$newheight,$width, $height);
         imagegif($tmp, $path);
     }
     else
     {
         return false;
     }
     return true;
     imagedestroy($image);
     imagedestroy($tmp);
}

Trong function ImageResize cũng tương đối đơn giản, chỉ việc sử dụng mấy hàm cắt hình, tạo hình thôi, các bạn có thể tìm hiểu thêm từng tính năng của từng các hàm của nó nhé
- list($width, $height) = getimagesize($tmp_name) :  Dùng lấy ra width,height của tấm hình upload
- $path = $path_file."/".$name; nhớ đặt đường dẫn lưu hình nhé

Các bạn có thể print_r từng chổ để biết rõ hơn trong function trên 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)