php上傳圖片后,如果圖片大於50kb則進行壓縮


if($size > 51200){
  //壓縮圖片
  $uploadfile = $imgDir.$filename;

  //圖片路徑
  $uploaddir_resize = 'account_imgs/';
  $uploadfile_resize = $uploaddir_resize.$filename;
  //echo $uploaddir_resize;
  function resizeImage($uploadfile,$maxwidth,$maxheight,$filename)
  {
    //取得當前圖片大小
    $width = imagesx($uploadfile);
    $height = imagesy($uploadfile);

    //壓縮比值

    $i=0.5;
    //生成縮略圖的大小
    if(($width > $maxwidth) || ($height > $maxheight))
    {
    /*
      $widthratio = $maxwidth/$width;
      $heightratio = $maxheight/$height;

      if($widthratio < $heightratio)
      {
        $ratio = $widthratio;
      }
      else
      {
        $ratio = $heightratio;
      }

      $newwidth = $width * $ratio;
      $newheight = $height * $ratio;
      */
      $newwidth = $width * $i;
      $newheight = $height * $i;
      if(function_exists("imagecopyresampled"))
      {
        $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
        //echo $uploaddir_resize;
        imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
      }
      else
      {
        $uploaddir_resize = imagecreate($newwidth, $newheight);
        imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
      }

      ImageJpeg ($uploaddir_resize,$filename);
      ImageDestroy ($uploaddir_resize);
    }
    else
    {
      ImageJpeg ($uploadfile,$filename);
    }
  }
  $pic_width_max = 120;
  $pic_height_max = 90;
  $file_type = $_FILES["file"]['type'];
  if($_FILES["file"]['size']){
    if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg")
    {
      //$im = imagecreatefromjpeg($_FILES['file']['tmp_name']);
      $im = imagecreatefromjpeg($uploadfile);
    }
    else if($file_type == "image/x-png")
    {
      //$im = imagecreatefrompng($_FILES['file']['tmp_name']);
      $im = imagecreatefromjpeg($uploadfile);
    }
    else if($file_type == "image/gif")
    {
      //$im = imagecreatefromgif($_FILES['file']['tmp_name']);
      $im = imagecreatefromjpeg($uploadfile);
    }
    else//默認jpg
    {
      $im = imagecreatefromjpeg($uploadfile);
    }

    if($im)
    {
      ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);
      ImageDestroy ($im);
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM