上传时更改图像尺寸

时间:2015-06-02 18:10:04

标签: php

我编写的代码可以从网址上传图片,但我需要在上传时将图片尺寸更改为250px * 250px

如何更改我的代码呢?

示例:如果我上传了130px * 185px尺寸的图片,则会自动将250px *250px保存在我的上传目录中。

我使用的代码是:

<?php
  /* photo uploader*/

  if($_POST["submit"]){
    $pic = trim($_POST["pic_url"]);

    if($pic){
      $photo = fopen($pic,"rb");

      if($photo){
        $valid_exts = array("jpg","jpeg","gif","png","Bmp","TIFF"); // default image only extensions

        if($valid_exts){
          $newpic = fopen("../../cat/adventure/images/" . basename($pic), "wb"); // replace "downloads" with whatever directory you wish.

          if($newpic){
            while(!feof($photo)){
              // Write the url file to the directory.
              fwrite($newpic,fread($photo,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
            }
          }
        }
      }
    }
  }
?>

1 个答案:

答案 0 :(得分:0)

您可以使用以下通用功能:

include_once("ak_php_img_lib_1.0.php");
$target_file = "uploads/$fileName";
$resized_file = "uploads/resized_$fileName";
$wmax = 200;
$hmax = 150;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);


<?php
// Function for resizing jpg, gif, or png image files
function ak_img_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(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
}
?>
相关问题