[PHP] 縮圖

Sample code

<?php
/**
* @file name    Resizing Images in PHP
* @create date  20160229
*/

if(isset($_POST["submit"])) {
  $v_upload_ok   = 1;
  $v_target_dir  = "file/";                     // 欲上傳存放的目錄位置
  $v_upload_file = $_FILES['uploaded_file'];    // 上傳檔案
  $v_file_name   = $v_upload_file["name"];      // 檔案原始名稱
  $v_file_type   = $v_upload_file["type"];      // 檔案類型
  $v_file_size   = $v_upload_file["size"];      // 檔案原始大小
  $v_explode     = explode(".", $v_file_name);
  $v_file_ext    = end( $v_explode );           // 檔案副檔名
  $v_file_tmp    = $v_upload_file["tmp_name"];  // 檔案暫存資料夾位置
  $v_file_error  = $v_upload_file["error"];     // 檔案上傳錯誤代碼顯示
  
  // echo "<pre>";
  // print_r($v_upload_file);
  // echo "</pre>"; 

  $v_target_file  = $v_target_dir . "target.".$v_file_ext;
  $v_resized_file = $v_target_dir . "resize.".$v_file_ext;
  
  $check = getimagesize($v_file_tmp);
  if( $check !== false ) {
    echo "<h2>File is an image - " . $check["mime"] . "." . "</h2>";
    move_uploaded_file($v_file_tmp, $v_target_file);
    image_resize($v_target_file, $v_resized_file, 150, 150, $v_file_ext);
    $v_upload_ok = 1;

  } else {
    echo "<h2>File is not an image.</h2>";
    $v_upload_ok = 0;
  }
  echo "<h2>";
  echo ($v_upload_ok == 0) ? ("Upload failed !") : ("Upload Successful !");
  echo "</h2>";
} //end

function image_resize($target, $newcopy, $w, $h, $ext) {
    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){ 
      $img = imagecreatefromgif($target);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($target);
    } else { 
      $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>example</title>
</head>
<body>
<form action="example.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="uploaded_file">
    <input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

Source

Image Resize Function Tutorial jpg gif png Change Size (**範例來源)
php實現的非常好用的圖片大小調整(image resize)函數
Função imagecopyresampled() do PHP cortando no lugar errado
PHP 5 File Upload

Image Source

[TUTORIAL] Cropping and Resizing Images in PHP

沒有留言:

技術提供:Blogger.