linux中tinypng圖片壓縮的例子

來源:互聯網
上載者:User

多的一般是圖片,圖片的壓縮比越大 ,訪問頁面速度會越快。wordpress下有相關的如WP Smush.it可以用於圖片壓縮,不過對於壓縮比例和保真層度來看,不如tinypng 。其對wordpress也提供了相應的外掛程式,不過免費版每個信箱使用者每月只提供五百個請求的壓縮。這裡結合其官方API ,做了一個shell版本的小工具,另外根據之前的php上傳及tinypng的php API也寫了一個web版的工具。

一、shell 版本

通過CURL請求,直接執行請求API URL時:

[root@361way tmp]# curl -i --user api:aSiDFS1VD1UfX7pIPdoDFSvoaYTaAvN --data-binary @delrepo2.png https://api.tinypng.com/shrink


執行結果 HTTP/1.1 100 Continue


HTTP/1.1 201 Created
Cache-Control: no-cache
Compression-Count: 2
Content-Type: application/json; charset=utf-8
Date: Wed, 04 Mar 2015 03:13:34 GMT
Location: https://api.tinypng.com/output/3molv9psquoqou8u.png
Server: Apache/2
Strict-Transport-Security: max-age=31536000
X-Powered-By: Voormedia (voormedia.com/jobs)
Content-Length: 158
Connection: keep-alive
{"input":{"size":10628,"type":"image/png"},"output":{"size":7865,"type":"image/png","ratio":0.74,"url":"https://api.tinypng.com/output/3molv9psquoqou8u.png"}}
其中Location地址為執行後返回壓縮後的圖片在伺服器上存放的地址。最後可以通過wget或curl 將該地址從遠程取回來。

以下是寫的shell 版,如下 :

#!/bin/bash
Help()
{
   cat << EOF
   ====================================================================
   Usage:  tinpny.sh  input.png output.png
   ====================================================================
EOF
}
if [ $# != 2 ];then
    Help
else
    httpcont=`date +%s`
    url=`curl --silent -i --user api:aSiDFS1VD1UfX7pIPdoDFSvoaY_TaAvN --data-binary @$1 https://api.tinypng.com/shrink |grep Location|awk '{print $2}'| tr -d '\r'`
    echo $url
    wget $url -O $2
fi


二、php版

可以先參看PHP圖片上傳程式(完整版) ,這裡使用的是PHP with curl API版,代碼如下:

<?php
/******************************************************************************
參數說明:
$max_file_size  : 上傳檔案大小限制, 單位BYTE
$destination_folder : 上傳檔案路徑
$watermark   : 是否附加浮水印(1為加浮水印,其他為不加浮水印);
使用說明:
1. 將PHP.INI檔案裡面的"extension=php_gd2.dll"一行前面的;號去掉,因為我們要用到GD庫;
2. 將extension_dir =改為你的php_gd2.dll所在目錄;
******************************************************************************/
//上傳檔案類型列表
$uptypes=array(
    'image/jpg',
    'image/jpeg',
    'image/png',
    'image/pjpeg',
    'image/gif',
    'image/bmp',
    'image/x-png'
);
$max_file_size=2000000;     //上傳檔案大小限制, 單位BYTE
$destination_folder="uploadimg/"; //上傳檔案路徑
$watermark=2;      //是否附加浮水印(1為加浮水印,其他為不加浮水印);
$watertype=1;      //浮水印類型(1為文字,2為圖片)
$waterposition=1;     //浮水印位置(1為左下角,2為右下角,3為左上方,4為右上方,5為置中);
$waterstring="http://www.361way.com/";  //浮水印字串
$waterimg="361way.gif";    //浮水印圖片
$imgpreview=1;      //是否產生預覽圖(1為產生,其他為不產生);
$imgpreviewsize=1/2;    //縮圖比例
?>
<?php
function Compressimg($input,$output)
{
    $key = "aSiDFS1VD1UfX7pIPdoDFSvoaY_TaAvN";
    $request = curl_init();
    curl_setopt_array($request, array(
      CURLOPT_URL => "https://api.tinypng.com/shrink",
      CURLOPT_USERPWD => "api:" . $key,
      CURLOPT_POSTFIELDS => file_get_contents($input),
      CURLOPT_BINARYTRANSFER => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HEADER => true,
      /* Uncomment below if you have trouble validating our SSL certificate.
         Download cacert.pem from: http://curl.haxx.se/ca/cacert.pem */
      // CURLOPT_CAINFO => __DIR__ . "/cacert.pem",
      CURLOPT_SSL_VERIFYPEER => true
    ));
    $response = curl_exec($request);
    if (curl_getinfo($request, CURLINFO_HTTP_CODE) === 201) {
      /* Compression was successful, retrieve output from Location header. */
      $headers = substr($response, 0, curl_getinfo($request, CURLINFO_HEADER_SIZE));
      foreach (explode("\r\n", $headers) as $header) {
        if (substr($header, 0, 10) === "Location: ") {
          $request = curl_init();
          curl_setopt_array($request, array(
            CURLOPT_URL => substr($header, 10),
            CURLOPT_RETURNTRANSFER => true,
            /* Uncomment below if you have trouble validating our SSL certificate. */
            // CURLOPT_CAINFO => __DIR__ . "/cacert.pem",
            CURLOPT_SSL_VERIFYPEER => true
          ));
          file_put_contents($output, curl_exec($request));
        }
      }
    } else {
        print(curl_error($request));
      /* Something went wrong! */
      print("Compression failed");
    }
}
?>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>361way圖片上傳程式</title>
<style type="text/css">
<!--
body
{
     font-size: 9pt;
}
input
{
     background-color: #66CCFF;
     border: 1px inset #CCCCCC;
}
-->
</style>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="upform">
  上傳檔案:
  <input name="upfile" type="file">
  <input type="submit" value="上傳"><br>
  允許上傳的檔案類型為:<?php echo implode(',',$uptypes)?>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
    //是否存在檔案
    {
         echo "圖片不存在!";
         exit;
    }
    $file = $_FILES["upfile"];
    if($max_file_size < $file["size"])
    //檢查檔案大小
    {
        echo "檔案太大!";
        exit;
    }
    if(!in_array($file["type"], $uptypes))
    //檢查檔案類型
    {
        echo "檔案類型不符!".$file["type"];
        exit;
    }
#    if(file_exists($_FILES["upfile"][name]))
#    {
#        echo "檔案名稱已存在";
#    }
    if(!file_exists($destination_folder))
    {
        mkdir($destination_folder);
    }
    $filename=$file["tmp_name"];
    $upfile_name=$file["name"];
    $image_size = getimagesize($filename);
    $pinfo=pathinfo($file["name"]);
    $ftype=$pinfo['extension'];
    $destination = $destination_folder.time().".".$ftype;
    if (file_exists($destination) && $overwrite != true)
    {
        echo "同名檔案已經存在了";
        exit;
    }
    if(!move_uploaded_file ($filename, $destination))
    {
        echo "移動檔案出錯";
        exit;
    }
    $pinfo=pathinfo($destination);
    $fname=$pinfo[basename];
    echo " <font color=red>已經成功上傳</font><br>檔案名稱:  <font color=blue>".$destination_folder.$fname."</font><br>";
    echo " 寬度:".$image_size[0];
    echo " 長度:".$image_size[1];
    echo "<br> 大小:".$file["size"]." bytes";
    if($watermark==1)
    {
        $iinfo=getimagesize($destination,$iinfo);
        $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
        $white=imagecolorallocate($nimage,255,255,255);
        $black=imagecolorallocate($nimage,0,0,0);
        $red=imagecolorallocate($nimage,255,0,0);
        imagefill($nimage,0,0,$white);
        switch ($iinfo[2])
        {
            case 1:
            $simage =imagecreatefromgif($destination);
            break;
            case 2:
            $simage =imagecreatefromjpeg($destination);
            break;
            case 3:
            $simage =imagecreatefrompng($destination);
            break;
            case 6:
            $simage =imagecreatefromwbmp($destination);
            break;
            default:
            die("不支援的檔案類型");
            exit;
        }
        imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
        imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);
        switch($watertype)
        {
            case 1:   //加浮水印字串
            imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
            break;
            case 2:   //加浮水印圖片
            $simage1 =imagecreatefromgif("361way.gif");
            imagecopy($nimage,$simage1,0,0,0,0,85,15);
            imagedestroy($simage1);
            break;
        }
        switch ($iinfo[2])
        {
            case 1:
            //imagegif($nimage, $destination);
            imagejpeg($nimage, $destination);
            break;
            case 2:
            imagejpeg($nimage, $destination);
            break;
            case 3:
            imagepng($nimage, $destination);
            break;
            case 6:
            imagewbmp($nimage, $destination);
            //imagejpeg($nimage, $destination);
            break;
        }
        //覆蓋原上傳檔案
        imagedestroy($nimage);
        imagedestroy($simage);
    }
    $output=$destination_folder.$upfile_name;
    Compressimg($destination,$output);
    unlink($destination);
    if($imgpreview==1)
    {
    echo "<br>圖片預覽:<br>";
    echo "<img src=\"".$output."\" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);
    echo " alt=\"圖片預覽:\r檔案名稱:".$output."\r上傳時間:\">";
    }
}
?>
</body>
</html>
最後:

官方還提供了Java、ruby、node.js、python版的API,本來想使用下python版,不過本地的使用python版本是2.7版本的,而官方提供的是python3.x版本的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.