当前位置:首页 > linux教程 > 列表

linux中tinypng图片压缩的例子

发布:smiling 来源: PHP粉丝网  添加日期:2015-04-21 11:26:17 浏览: 评论:0 

TinyPNG一个压缩PNG工具了,TinyPNG为了达到更小的文件大小进行了有损压缩,尽管在质量上有轻微的下降,但裸眼看不出来,下面我们就来看看linux中tinypng图片压缩的例子.

多的一般是图片,图片的压缩比越大,访问页面速度会越快,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

  1. HTTP/1.1 201 Created 
  2. Cache-Control: no-cache 
  3. Compression-Count: 2 
  4. Content-Type: application/json; charset=utf-8 
  5. Date: Wed, 04 Mar 2015 03:13:34 GMT 
  6. Location: https://api.tinypng.com/output/3molv9psquoqou8u.png 
  7. Server: Apache/2 
  8. Strict-Transport-Security: max-age=31536000 
  9. X-Powered-By: Voormedia (voormedia.com/jobs) 
  10. Content-Length: 158 
  11. Connection: keep-alive 
  12. {"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 版,如下:

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

二、php版

可以先参看PHP图片上传程序(完整版),这里使用的是PHP with curl API版,代码如下:

  1. <?php 
  2. /****************************************************************************** 
  3. 参数说明: 
  4. $max_file_size  : 上传文件大小限制, 单位BYTE 
  5. $destination_folder : 上传文件路径 
  6. $watermark   : 是否附加水印(1为加水印,其他为不加水印); 
  7. 使用说明: 
  8. 1. 将PHP.INI文件里面的"extension=php_gd2.dll"一行前面的;号去掉,因为我们要用到GD库; 
  9. 2. 将extension_dir =改为你的php_gd2.dll所在目录; 
  10. ******************************************************************************/ 
  11. //上传文件类型列表 
  12. $uptypes=array( 
  13.     'image/jpg', 
  14.     'image/jpeg', 
  15.     'image/png', 
  16.     'image/pjpeg', 
  17.     'image/gif', 
  18.     'image/bmp', 
  19.     'image/x-png' 
  20. ); 
  21. $max_file_size=2000000;     //上传文件大小限制, 单位BYTE 
  22. $destination_folder="uploadimg/"; //上传文件路径 
  23. $watermark=2;      //是否附加水印(1为加水印,其他为不加水印); 
  24. $watertype=1;      //水印类型(1为文字,2为图片) 
  25. $waterposition=1;     //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中); 
  26. $waterstring="http://www.361way.com/";  //水印字符串 
  27. $waterimg="361way.gif";    //水印图片 
  28. $imgpreview=1;      //是否生成预览图(1为生成,其他为不生成); 
  29. $imgpreviewsize=1/2;    //缩略图比例 
  30. ?> 
  31. <?php 
  32. function Compressimg($input,$output) 
  33. { 
  34.     $key = "aSiDFS1VD1UfX7pIPdoDFSvoaY_TaAvN"; 
  35.     $request = curl_init(); 
  36.     curl_setopt_array($request, array( 
  37.       CURLOPT_URL => "https://api.tinypng.com/shrink", 
  38.       CURLOPT_USERPWD => "api:" . $key, 
  39.       CURLOPT_POSTFIELDS => file_get_contents($input), 
  40.       CURLOPT_BINARYTRANSFER => true, 
  41.       CURLOPT_RETURNTRANSFER => true, 
  42.       CURLOPT_HEADER => true, 
  43.       /* Uncomment below if you have trouble validating our SSL certificate. 
  44.          Download cacert.pem from: http://curl.haxx.se/ca/cacert.pem */ 
  45.       // CURLOPT_CAINFO => __DIR__ . "/cacert.pem", 
  46.       CURLOPT_SSL_VERIFYPEER => true 
  47.     )); 
  48.     $response = curl_exec($request); 
  49.     if (curl_getinfo($request, CURLINFO_HTTP_CODE) === 201) { 
  50.       /* Compression was successful, retrieve output from Location header. */ 
  51.       $headers = substr($response, 0, curl_getinfo($request, CURLINFO_HEADER_SIZE)); 
  52.       foreach (explode("\r\n", $headers) as $header) { 
  53.         if (substr($header, 0, 10) === "Location: ") { 
  54.           $request = curl_init(); 
  55.           curl_setopt_array($request, array( 
  56.             CURLOPT_URL => substr($header, 10), 
  57.             CURLOPT_RETURNTRANSFER => true, 
  58.             /* Uncomment below if you have trouble validating our SSL certificate. */ 
  59.             // CURLOPT_CAINFO => __DIR__ . "/cacert.pem", 
  60.             CURLOPT_SSL_VERIFYPEER => true 
  61.           )); 
  62.           file_put_contents($output, curl_exec($request)); 
  63.         } 
  64.       } 
  65.     } else { 
  66.         print(curl_error($request)); 
  67.       /* Something went wrong! */ 
  68.       print("Compression failed"); 
  69.     } 
  70. } 
  71. ?> 
  72. <html> 
  73. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  74. <head> 
  75. <title>361way图片上传程序</title> 
  76. <style type="text/css"> 
  77. <!-- 
  78. body 
  79. { 
  80.      font-size: 9pt; 
  81. } 
  82. input 
  83. { 
  84.      background-color: #66CCFF; 
  85.      border: 1px inset #CCCCCC; 
  86. } 
  87. --> 
  88. </style> 
  89. </head> 
  90. <body> 
  91. <form enctype="multipart/form-data" method="post" name="upform"> 
  92.   上传文件: 
  93.   <input name="upfile" type="file"> 
  94.   <input type="submit" value="上传"><br> 
  95.   允许上传的文件类型为:<?php echo implode(',',$uptypes)?> 
  96. </form> 
  97. <?php 
  98. if ($_SERVER['REQUEST_METHOD'] == 'POST') 
  99. { 
  100.     if (!is_uploaded_file($_FILES["upfile"][tmp_name])) 
  101.     //是否存在文件 
  102.     { 
  103.          echo "图片不存在!"; 
  104.          exit; 
  105.     } 
  106.     $file = $_FILES["upfile"]; 
  107.     if($max_file_size < $file["size"]) 
  108.     //检查文件大小 
  109.     { 
  110.         echo "文件太大!"; 
  111.         exit; 
  112.     } 
  113.     if(!in_array($file["type"], $uptypes)) 
  114.     //检查文件类型 
  115.     { 
  116.         echo "文件类型不符!".$file["type"]; 
  117.         exit; 
  118.     } 
  119. #    if(file_exists($_FILES["upfile"][name])) 
  120. #    { 
  121. #        echo "文件名已存在"; 
  122. #    } 
  123.     if(!file_exists($destination_folder)) 
  124.     { 
  125.         mkdir($destination_folder); 
  126.     } 
  127.     $filename=$file["tmp_name"]; 
  128.     $upfile_name=$file["name"]; 
  129.     $image_size = getimagesize($filename); 
  130.     $pinfo=pathinfo($file["name"]); 
  131.     $ftype=$pinfo['extension']; 
  132.     $destination = $destination_folder.time().".".$ftype; 
  133.     if (file_exists($destination) && $overwrite != true) 
  134.     { 
  135.         echo "同名文件已经存在了"; 
  136.         exit; 
  137.     } 
  138.     if(!move_uploaded_file ($filename, $destination)) 
  139.     { 
  140.         echo "移动文件出错"; 
  141.         exit; 
  142.     } 
  143.     $pinfo=pathinfo($destination); 
  144.     $fname=$pinfo[basename]; 
  145.     echo " <font color=red>已经成功上传</font><br>文件名:  <font color=blue>".$destination_folder.$fname."</font><br>"; 
  146.     echo " 宽度:".$image_size[0]; 
  147.     echo " 长度:".$image_size[1]; 
  148.     echo "<br> 大小:".$file["size"]." bytes"; 
  149.     if($watermark==1) 
  150.     { 
  151.         $iinfo=getimagesize($destination,$iinfo); 
  152.         $nimage=imagecreatetruecolor($image_size[0],$image_size[1]); 
  153.         $white=imagecolorallocate($nimage,255,255,255); 
  154.         $black=imagecolorallocate($nimage,0,0,0); 
  155.         $red=imagecolorallocate($nimage,255,0,0); 
  156.         imagefill($nimage,0,0,$white); 
  157.         switch ($iinfo[2]) 
  158.         { 
  159.             case 1: 
  160.             $simage =imagecreatefromgif($destination); 
  161.             break; 
  162.             case 2: 
  163.             $simage =imagecreatefromjpeg($destination); 
  164.             break; 
  165.             case 3: 
  166.             $simage =imagecreatefrompng($destination); 
  167.             break; 
  168.             case 6: 
  169.             $simage =imagecreatefromwbmp($destination); 
  170.             break; 
  171.             default: 
  172.             die("不支持的文件类型"); 
  173.             exit; 
  174.         } 
  175.         imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]); 
  176.         imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white); 
  177.         switch($watertype) 
  178.         { 
  179.             case 1:   //加水印字符串 
  180.             imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black); 
  181.             break; 
  182.             case 2:   //加水印图片 
  183.             $simage1 =imagecreatefromgif("361way.gif"); 
  184.             imagecopy($nimage,$simage1,0,0,0,0,85,15); 
  185.             imagedestroy($simage1); 
  186.             break; 
  187.         } 
  188.         switch ($iinfo[2]) 
  189.         { 
  190.             case 1: 
  191.             //imagegif($nimage, $destination); 
  192.             imagejpeg($nimage, $destination); 
  193.             break; 
  194.             case 2: 
  195.             imagejpeg($nimage, $destination); 
  196.             break; 
  197.             case 3: 
  198.             imagepng($nimage, $destination); 
  199.             break; 
  200.             case 6: 
  201.             imagewbmp($nimage, $destination); 
  202.             //imagejpeg($nimage, $destination); 
  203.             break; 
  204.         } 
  205.         //覆盖原上传文件 
  206.         imagedestroy($nimage); 
  207.         imagedestroy($simage); 
  208.     }  //phpfensi.com 
  209.     $output=$destination_folder.$upfile_name; 
  210.     Compressimg($destination,$output); 
  211.     unlink($destination); 
  212.     if($imgpreview==1) 
  213.     { 
  214.     echo "<br>图片预览:<br>"; 
  215.     echo "<img src=\"".$output."\" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize); 
  216.     echo " alt=\"图片预览:\r文件名:".$output."\r上传时间:\">"; 
  217.     } 
  218. } 
  219. ?> 
  220. </body> 
  221. </html> 

最后:官方还提供了Java、ruby、node.js、python版的API,本来想使用下python版,不过本地的使用python版本是2.7版本的,而官方提供的是python3.x版本的.

Tags: linux图片压缩 tinypng图片压缩

分享到: