圖片上傳自動壓縮php,上傳圖片壓縮怎麼弄

本文目錄一覽:

PHP、HTML5上傳圖片自動壓縮問題

給你個圖片處理的類吧,圖片剪裁處理後,也就等於將圖片壓縮了。

/**

* 圖像處理類

* ============================================================================

 * Copyright 2014 大秦科技,並保留所有權利。

 * 網站地址: ;

 * ============================================================================

*/

class Image{

    //生成縮略圖的方式

    public $thumbType;

    //縮略圖的寬度

    public $thumbWidth;

    //縮略圖的高度

    public $thumbHeight;

    //生成縮略圖文件名後綴

    public $thumbEndFix;

    //縮略圖文件前綴

    public $thumbPreFix;

    /**

     * 構造函數

     */

    public function __construct(){

        $this-thumbType = 1;

        $this-thumbWidth = 120;

        $this-thumbHeight = 60;

        $this-thumbPreFix =”;

        $this-thumbEndFix =  ‘_thumb’;

    }

    /**

     * 檢測是否為圖像文件

     * @param $img 圖像

     * @return bool

     */

    private function check($img){

        $type = array(“.jpg”, “.jpeg”, “.png”, “.gif”);

        $imgType = strtolower(strrchr($img, ‘.’));

        return extension_loaded(‘gd’)  file_exists($img)  in_array($imgType, $type);

    }

    /**

     * 獲得縮略圖的尺寸信息

     * @param $imgWidth 原圖寬度

     * @param $imgHeight 原圖高度

     * @param $thumbWidth 縮略圖寬度

     * @param $thumbHeight 縮略圖的高度

     * @param $thumbType 處理方式

     * 1 固定寬度  高度自增 2固定高度  寬度自增 3固定寬度  高度裁切

     * 4 固定高度 寬度裁切 5縮放最大邊 原圖不裁切

     * @return mixed

     */

    private function thumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType){

        //初始化縮略圖尺寸

        $w = $thumbWidth;

        $h = $thumbHeight;

        //初始化原圖尺寸

        $cuthumbWidth = $imgWidth;

        $cuthumbHeight = $imgHeight;

        switch ($thumbType) {

            case 1 :

                //固定寬度  高度自增

                $h = $thumbWidth / $imgWidth * $imgHeight;

                break;

            case 2 :

                //固定高度  寬度自增

                $w = $thumbHeight / $imgHeight * $imgWidth;

                break;

            case 3 :

                //固定寬度  高度裁切

                $cuthumbHeight = $imgWidth / $thumbWidth * $thumbHeight;

                break;

            case 4 :

                //固定高度  寬度裁切

                $cuthumbWidth = $imgHeight / $thumbHeight * $thumbWidth;

                break;

            case 5 :

                //縮放最大邊 原圖不裁切

                if (($imgWidth / $thumbWidth)  ($imgHeight / $thumbHeight)) {

                    $h = $thumbWidth / $imgWidth * $imgHeight;

                } elseif (($imgWidth / $thumbWidth)  ($imgHeight / $thumbHeight)) {

                    $w = $thumbHeight / $imgHeight * $imgWidth;

                } else {

                    $w = $thumbWidth;

                    $h = $thumbHeight;

                }

                break;

            default:

                //縮略圖尺寸不變,自動裁切圖片

                if (($imgHeight / $thumbHeight)  ($imgWidth / $thumbWidth)) {

                    $cuthumbWidth = $imgHeight / $thumbHeight * $thumbWidth;

                } elseif (($imgHeight / $thumbHeight)  ($imgWidth / $thumbWidth)) {

                    $cuthumbHeight = $imgWidth / $thumbWidth * $thumbHeight;

                }

//            }

        }

        $arr [0] = $w;

        $arr [1] = $h;

        $arr [2] = $cuthumbWidth;

        $arr [3] = $cuthumbHeight;

        return $arr;

    }

    /**

     * 圖片裁切處理

     * @param $img 原圖

     * @param string $outFile 另存文件名

     * @param string $thumbWidth 縮略圖寬度

     * @param string $thumbHeight 縮略圖高度

     * @param string $thumbType 裁切圖片的方式

     * 1 固定寬度  高度自增 2固定高度  寬度自增 3固定寬度  高度裁切

     * 4 固定高度 寬度裁切 5縮放最大邊 原圖不裁切 6縮略圖尺寸不變,自動裁切最大邊

     * @return bool|string

     */

    public function thumb($img, $outFile = ”, $thumbWidth = ”, $thumbHeight = ”, $thumbType = ”){

        if (!$this-check($img)) {

            return false;

        }

        //基礎配置

        $thumbType = $thumbType ? $thumbType : $this-thumbType;

        $thumbWidth = $thumbWidth ? $thumbWidth : $this-thumbWidth;

        $thumbHeight = $thumbHeight ? $thumbHeight : $this-thumbHeight;

        //獲得圖像信息

        $imgInfo = getimagesize($img);

        $imgWidth = $imgInfo [0];

        $imgHeight = $imgInfo [1];

        $imgType = image_type_to_extension($imgInfo [2]);

        //獲得相關尺寸

        $thumb_size = $this-thumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType);

        //原始圖像資源

        $func = “imagecreatefrom” . substr($imgType, 1);

        $resImg = $func($img);

        //縮略圖的資源

        if ($imgType == ‘.gif’) {

            $res_thumb = imagecreate($thumb_size [0], $thumb_size [1]);

            $color = imagecolorallocate($res_thumb, 255, 0, 0);

        } else {

            $res_thumb = imagecreatetruecolor($thumb_size [0], $thumb_size [1]);

            imagealphablending($res_thumb, false); //關閉混色

            imagesavealpha($res_thumb, true); //儲存透明通道

        }

        //繪製縮略圖X

        if (function_exists(“imagecopyresampled”)) {

            imagecopyresampled($res_thumb, $resImg, 0, 0, 0, 0, $thumb_size [0], $thumb_size [1], $thumb_size [2], $thumb_size [3]);

        } else {

            imagecopyresized($res_thumb, $resImg, 0, 0, 0, 0, $thumb_size [0], $thumb_size [1], $thumb_size [2], $thumb_size [3]);

        }

        //處理透明色

        if ($imgType == ‘.gif’) {

            imagecolortransparent($res_thumb, $color);

        }

        //配置輸出文件名

        $imgInfo = pathinfo($img);

        $outFile = $outFile ? $outFile :dirname($img).’/’. $this-thumbPreFix . $imgInfo[‘filename’] . $this-thumbEndFix . “.” . $imgInfo[‘extension’];

        Files::create(dirname($outFile));

        $func = “image” . substr($imgType, 1);

        $func($res_thumb, $outFile);

        if (isset($resImg))

            imagedestroy($resImg);

        if (isset($res_thumb))

            imagedestroy($res_thumb);

        return $outFile;

    }

}

PHP網站上傳圖片自動壓縮,怎麼編程啊,求指

這裡會使用到三個文件:

connect.php:連接資料庫

test_upload.php:執行SQL語句

upload_img.php:上傳圖片並壓縮

三個文件代碼如下:

連接資料庫:connect.php

?php

$db_host = ”;

$db_user = ”;

$db_psw = ”;

$db_name = ”;

$db_port = ”;

$sqlconn=new mysqli($db_host,$db_user,$db_psw,$db_name);

$q=”set names utf8;”;

$result=$sqlconn-query($q);

if (mysqli_connect_errno()) {

 printf(“Connect failed: %s\n”, mysqli_connect_error());

 exit();

}

?

當然使用一些封裝的資料庫類也是可以的。

執行SQL語句:test_upload.php

?php

require (“connect.php”);

require (“upload_img.php”);

$real_img=$uploadfile; 

$small_img=$uploadfile_resize;

$insert_sql = “insert into img (real_img,small_img) values (?,?)”;

$result = $sqlconn – prepare($insert_sql);

$result – bind_param(“ss”, $real_img,$small_img);

$result – execute();

?

上傳圖片並壓縮:upload_img.php

?php 

//設置文件保存目錄

$uploaddir = “upfiles/”; 

//設置允許上傳文件的類型

$type=array(“jpg”,”gif”,”bmp”,”jpeg”,”png”); 

 

//獲取文件後綴名函數 

function fileext($filename) 

 return substr(strrchr($filename, ‘.’), 1); 

 

//生成隨機文件名函數 

function random($length) 

 $hash = ‘CR-‘; 

 $chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz’; 

 $max = strlen($chars) – 1; 

 mt_srand((double)microtime() * 1000000); 

 for($i = 0; $i  $length; $i++) 

 { 

  $hash .= $chars[mt_rand(0, $max)]; 

 } 

 return $hash; 

 

$a=strtolower(fileext($_FILES[‘filename’][‘name’])); 

 

//判斷文件類型 

if(!in_array(strtolower(fileext($_FILES[‘filename’][‘name’])),$type)) 

 $text=implode(“,”,$type); 

 $ret_code=3;//文件類型錯誤

 $page_result=$text;

 $retArray = array(‘ret_code’ = $ret_code,’page_result’=$page_result);

 $retJson = json_encode($retArray);

 echo $retJson;

 return;

 

//生成目標文件的文件名 

else

 $filename=explode(“.”,$_FILES[‘filename’][‘name’]); 

 do

 { 

  $filename[0]=random(10); //設置隨機數長度 

  $name=implode(“.”,$filename); 

  //$name1=$name.”.Mcncc”; 

  $uploadfile=$uploaddir.$name; 

 } 

 

 while(file_exists($uploadfile)); 

 

 if (move_uploaded_file($_FILES[‘filename’][‘tmp_name’],$uploadfile)) 

 { 

  if(is_uploaded_file($_FILES[‘filename’][‘tmp_name’])) 

  {

   $ret_code=1;//上傳失敗

  } 

 else

 {//上傳成功

  $ret_code=0;

 } 

 } 

$retArray = array(‘ret_code’ = $ret_code);

$retJson = json_encode($retArray);

echo $retJson;

}

 

//壓縮圖片

 

$uploaddir_resize=”upfiles_resize/”;

$uploadfile_resize=$uploaddir_resize.$name;

 

//$pic_width_max=120;

//$pic_height_max=90;

//以上與下面段注釋可以聯合使用,可以使圖片根據計算出來的比例壓縮

 

$file_type=$_FILES[“filename”][‘type’];

 

function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)

{

 //取得當前圖片大小

 $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);

   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,$name);

  ImageDestroy ($uploaddir_resize);

 }

 else

 {

  ImageJpeg ($uploadfile,$name);

 }

}

 

 

 

if($_FILES[“filename”][‘size’])

{

 if($file_type == “image/pjpeg”||$file_type == “image/jpg”|$file_type == “image/jpeg”)

 {

  //$im = imagecreatefromjpeg($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 elseif($file_type == “image/x-png”)

 {

  //$im = imagecreatefrompng($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 elseif($file_type == “image/gif”)

 {

  //$im = imagecreatefromgif($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 else//默認jpg

 {

  $im = imagecreatefromjpeg($uploadfile);

 }

 if($im)

 {

  ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);

  

  ImageDestroy ($im);

 }

?

請按照現實情況更改connect.php,test_upload.php中對應的信息。

望採納,謝謝。

如何利用php把上傳的圖片壓縮

?php

// The file

$filename = ‘test.jpg’;

$percent = 0.5;

// Content type

header(‘Content-Type: image/jpeg’);

// Get new dimensions

list($width, $height) = getimagesize($filename);

$new_width = $width * $percent;

$new_height = $height * $percent;

// Resample

$image_p = imagecreatetruecolor($new_width, $new_height);

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output

imagejpeg($image_p, null, 100);

?

php圖片上傳能用代碼壓縮圖片文件的大小嗎

圖片的格式是多變的,但是壓縮圖片的方式不變,壓縮軟體壓縮圖片一致都是那樣,我將操作步驟寫下來了,樓主可以看看

1、安裝相對應的輔助工具(迅捷圖片壓縮軟體)運行工具;

2、打開工具,看到頁面上的圖片壓縮選項,點擊這個藍色的按鈕進入將要實行操作的頁面。

3、在頁面上點擊選擇文件按鈕,或是選擇文件夾按鈕,都可以將存放圖片文件的文件夾打開,然後對圖片進行選擇。

4、選擇文件時我們按住多選鍵Ctrl,選擇我們需要壓縮的圖片添加到頁面中間的位置。

5、做到這一步了,下面我們可以對壓縮圖片的壓縮選項做一個選擇,可以轉換圖片的格式,轉化為png或者是jpg,將圖片壓縮可以選擇的壓縮選項如下。

6、將所有的參數設置完成之後我們點擊頁面上的「開始壓縮按鈕就可以進行壓縮了。

日常使用的壓縮圖片的辦法是將圖片壓縮為壓縮包,在使用是還要對其解壓才能使用,這種壓縮方法壓縮圖片不同點在於不會將圖片文件壓縮為壓縮包,能將圖片最大限度的縮小,圖片的狀態不會改變。

php上傳圖片壓縮

html里加一個表單,然後提交到處理上傳文件的upload.php

類似下面這樣

from action=”upload.php” enctype=”multipart/from-data” method=”post”

input type=”file” name=”file3″/

/from

然後upload.php里先處理圖片上傳,最終保存一份原始圖片文件在伺服器上,接著就把文件路徑什麼的傳到你的這個函數里處理圖片就OK了

php圖片上傳後被壓縮了,變得不清晰了,怎麼解決

如果清晰的上傳後,不清晰,,那就是設置的壓縮質量問題,,,如果是不清晰上傳了,這肯定不會清晰了。。。

找到上傳的設置里可以找到圖片壓縮比例。。。。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/185889.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-26 21:08
下一篇 2024-11-26 21:08

相關推薦

  • PHP和Python哪個好找工作?

    PHP和Python都是非常流行的編程語言,它們被廣泛應用於不同領域的開發中。但是,在考慮擇業方向的時候,很多人都會有一個問題:PHP和Python哪個好找工作?這篇文章將從多個方…

    編程 2025-04-29
  • PHP怎麼接幣

    想要在自己的網站或應用中接受比特幣等加密貨幣的支付,就需要對該加密貨幣擁有一定的了解,並使用對應的API進行開發。本文將從多個方面詳細闡述如何使用PHP接受加密貨幣的支付。 一、環…

    編程 2025-04-29
  • 使用PHP foreach遍歷有相同屬性的值

    本篇文章將介紹如何使用PHP foreach遍歷具有相同屬性的值,並給出相應的代碼示例。 一、基礎概念 在講解如何使用PHP foreach遍歷有相同屬性的值之前,我們需要先了解幾…

    編程 2025-04-28
  • PHP獲取301跳轉後的地址

    本文將為大家介紹如何使用PHP獲取301跳轉後的地址。301重定向是什麼呢?當我們訪問一個網頁A,但是它已經被遷移到了另一個地址B,此時若伺服器端做了301重定向,那麼你的瀏覽器在…

    編程 2025-04-27
  • PHP登錄頁面代碼實現

    本文將從多個方面詳細闡述如何使用PHP編寫一個簡單的登錄頁面。 1. PHP登錄頁面基本架構 在PHP登錄頁面中,需要包含HTML表單,用戶在表單中輸入賬號密碼等信息,提交表單後服…

    編程 2025-04-27
  • PHP與Python的比較

    本文將會對PHP與Python進行比較和對比分析,包括語法特性、優缺點等方面。幫助讀者更好地理解和使用這兩種語言。 一、語法特性 PHP語法特性: <?php // 簡單的P…

    編程 2025-04-27
  • PHP版本管理工具phpenv詳解

    在PHP項目開發過程中,我們可能需要用到不同版本的PHP環境來試驗不同的功能或避免不同版本的兼容性問題。或者我們需要在同一台伺服器上同時運行多個不同版本的PHP語言。但是每次手動安…

    編程 2025-04-24
  • PHP數組去重詳解

    一、array_unique函數 array_unique是php中常用的數組去重函數,它基於值來判斷元素是否重複,具體使用方法如下: $array = array(‘a’, ‘b…

    編程 2025-04-24
  • PHP導出Excel文件

    一、PHP導出Excel文件列寬調整 當我們使用PHP導出Excel文件時,有時需要調整單元格的列寬。可以使用PHPExcel類庫中的setWidth方法來設置單元格的列寬。下面是…

    編程 2025-04-24
  • php擴展庫初探

    一、什麼是php擴展庫? PHP擴展庫(PHP extension)是一些用C語言編寫的動態鏈接庫,用於擴展PHP的功能。PHP擴展庫使得PHP可以與各種資料庫系統相連、SMTP、…

    編程 2025-04-23

發表回復

登錄後才能評論