Examples of tinypng image compression in Linux

Source: Internet
Author: User
Tags curl curl api imagecopy imagejpeg ssl certificate tinypng

More generally is the picture, the picture compression ratio is bigger, accesses the page speed to be quicker. WordPress under the relevant such as WP smush.it can be used for picture compression, but for compression ratio and fidelity level, as tinypng. WordPress also provides the appropriate plug-ins, but the free version of each mailbox users only provide 500 requests per month compression. This combination of its official API, made a shell version of the gadget, in addition to the previous PHP upload and tinypng PHP API also wrote a web version of the tool.

First, Shell version

When the request API URL is executed directly through the Curl request:

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


Implementation results http/1.1 Continue


http/1.1 201 Created
Cache-control:no-cache
Compression-count:2
Content-type:application/json; Charset=utf-8
Date:wed, 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 "}}
Where the location address is the address that the compressed picture is stored on the server after it is executed. Finally, the address can be taken back from the remote by wget or curl.

The following is a shell version written, as follows:

#!/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 $} ' | Tr-d ' \ r '
Echo $url
wget $url-O $
Fi


Second, PHP version

You can see the PHP image upload program (full version), here is the PHP with Curl API version, the code is as follows:

<?php
/******************************************************************************
Parameter description:
$max _file_size: Upload file size limit, unit byte
$destination _folder: Upload file path
$watermark: Whether additional watermark (1 for Watermark, other for no watermark);
Instructions for use:
1. Remove the "Extension=php_gd2.dll" line in front of the php.ini file, because we need to use the GD library;
2. Change Extension_dir = to the directory where your Php_gd2.dll is located;
******************************************************************************/
Upload file Type list
$uptypes =array (
' Image/jpg ',
' Image/jpeg ',
' Image/png ',
' Image/pjpeg ',
' Image/gif ',
' Image/bmp ',
' Image/x-png '
);
$max _file_size=2000000; Upload file size limit, unit byte
$destination _folder= "uploadimg/"; Upload file path
$watermark = 2; Whether to add watermark (1 for Watermark, other for no watermark);
$watertype = 1; Watermark Type (1 for text, 2 for picture)
$waterposition = 1; Watermark position (1 is lower left corner, 2 is lower right corner, 3 is upper left corner, 4 is upper right corner, 5 is centered);
$waterstring = "http://www.361way.com/"; Watermark String
$waterimg = "361way.gif"; Watermark Picture
$imgpreview = 1; Whether to generate a preview diagram (1 is a build, others are not generated);
$imgpreviewsize =1/2; Thumbnail proportions
?>
<?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 are 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 is 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,) = = "Location:") {
$request = Curl_init ();
Curl_setopt_array ($request, Array (
Curlopt_url => substr ($header, 10),
Curlopt_returntransfer => True,
/* Uncomment below if you are 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");
}
}
?>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>361way Image Upload Program </title>
<style type= "Text/css" >
<!--
Body
{
font-size:9pt;
}
Input
{
Background-color: #66CCFF;
border:1px inset #CCCCCC;
}
-->
</style>
<body>
<form enctype= "Multipart/form-data" method= "post" name= "Upform" >
Upload file:
<input name= "upfile" type= "File" >
<input type= "Submit" value= "Upload" ><br>
The types of files allowed to upload are: <?php echo implode (', ', $uptypes)?>
</form>
<?php
if ($_server[' request_method '] = = ' POST ')
{
if (!is_uploaded_file ($_files["Upfile"][tmp_name))
Is there a file
{
echo "Picture does not exist!";
Exit
}
$file = $_files["Upfile"];
if ($max _file_size < $file ["size"])
Check File size
{
echo "file is too big!";
Exit
}
if (!in_array ($file ["type"], $uptypes))
Check file type
{
echo "file type does not match!". $file [' type '];
Exit
}
# if (file_exists ($_files["Upfile"][name))
#    {
# echo ' filename already exists ';
#    }
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 "file with the same name already exists";
Exit
}
if (!move_uploaded_file ($filename, $destination))
{
echo "Move file Error";
Exit
}
$pinfo =pathinfo ($destination);
$fname = $pinfo [basename];
echo "<font color=red> has been successfully uploaded </font><br> FileName: <font color=blue>". $destination _folder. $fname. " </font><br> ";
echo "width:". $image _size[0];
echo "Length:". $image _size[1];
echo "<br> size:". $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 ("Unsupported file type");
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://Add watermark String
Imagestring ($nimage, 2,3, $image _size[1]-15, $waterstring, $black);
Break
Case 2://Add watermark Picture
$simage 1 =imagecreatefromgif ("361way.gif");
Imagecopy ($nimage, $simage 1,0,0,0,0,85,15);
Imagedestroy ($simage 1);
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
}
Overwrite original upload file
Imagedestroy ($nimage);
Imagedestroy ($simage);
}
$output = $destination _folder. $upfile _name;
Compressimg ($destination, $output);
Unlink ($destination);
if ($imgpreview ==1)
{
echo "<br> picture preview:<br>";
echo "echo "alt=\" Picture preview: \ r filename: ". $output." \ r upload time: \ ">";
}
}
?>
</body>
At last:

The official also provided the Java, Ruby, node.js, Python version of the API, originally wanted to use the Python version, but the local use of the Python version is 2.7 version, and the official offer is python3.x version.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.