Application of Python in the Seven Cow Cloud Platform (ii) Image slimming

Source: Internet
Author: User

(a) Seven cow cloud Platform picture Slimming function Introduction: (Quoted from the official website)

Image for JPEG, PNG format

    1. Thin behind the resolution unchanged, the format is unchanged.
    2. The visual quality does not change.
    3. Reduced volume of images, saving CDN traffic

Website to the picture compression rate is very high, the official website to the "grape" picture slimming without changing the resolution and format of the case of compression rate of 65.49%, I tested a small figure in the later text will have, the original size in the "22kb" compressed after the " 18kb", according to the general situation, although the compression rate does not have the official website to give so exaggerated, but also can basically reach 80% around, so this compression rate is still very good.

(ii) Demand analysis

We can imagine a couple of scenarios

"1: When you load on the site need traffic, and the compression rate of 80% is almost direct to spend money *0.8, if the picture is many, then this will be able to save a lot of money"

"2: sometimes let the website upload their own passport photo/passport, often also limit the size of the photo, and this time if the size is beyond, generally only through the transfer format, cutting and so on. And seven of the pictures of the cattle in this case can have a role.

"3: Due to the introduction of seven cattle-the naked eye quality is not changed (highlighted above), then the size of many pictures today is quite scary, if stored on the hard disk is also a big expense, if the picture is thin, this can save a lot of hard disk overhead, compressed volume."

Summary: The above list of scenes is not difficult to see the image of thin body for us still have a lot of applications, the following is how to use in Python seven of the image slimming function of cattle introduced.

(iii) Preparation for use of this interface

Here's what you need to do in the previous blog. The application ofPython in the Seven Cow Cloud Platform (a) (portal) (Qiniu)

We need to use the Upload/authentication command with the Qiniu library. As well as the requests library to get processed images

Seven cow this interface is to pay, but very cheap, can first to their own account into the ¥1 to avoid the situation, the specific charge for ¥0.1/1000 times

(iv) Steps to resolve the problem

First, we first analyze the interface of the seven Qiniu API:

Http://xxx.xxx.glb.clouddn.com/xxx.jpg?imageslim <!-- The actual interface here is on the last side? Imageslim Front is the outer chain address and file name of the space-- 

It can be known that it is handled in the form of a file in our own bucket after the address of the outside of the chain add? Imageslim to get the compressed image

So the steps we're going to take are as follows:

1) Upload the image of the specified type into our bucket (to determine if it is JPEG and PNG format)-use split to parse the file suffix and upload to the file using the method uploaded to seven Qiniu in the previous article.

2) The external link address of the image to be uploaded

3) Prepare the params property of the requests library to add Imageslim to the link and request.

4) write the picture in binary form to the picture

(v) The implementation of the program, see the code below: operation of the picture or uptest.jpg

#Seven cow cloud "picture slimming" function of Python implementation method:#please get your own secret and access key for uploading images into space for processing#picture Slimming is a charge item of seven Qiniu, the price is ¥0.1/1000 test, please save 1 yuan to enter#Import SDK fromQiniuImportAuth,put_file,etagImportQiniu.configImportRequests#specify the format of the picture processing suffixpicu=['jpg','JPEG','PNG','PNG','JPEG','JPG']#UploaddefUpload (Bucket,path,filename,key,url): Token= Key.upload_token (bucket, filename, 3600)    Print('Uploading:') Reform,inform=put_file (token, filename, path)ifReform! =None:Print('the {}->>{} has been successfully'. Format (filename,bucket))Print("Working on your picture ...") URL=url +'/'+filename Path=path.split ('/') [-1] Download (url,path)Else:        Print('a small error has occurred here. Unable to upload :')                #DownloaddefDownload (url,path):ifUrl.split ('.') [-1]inchPicu:r= Requests.get (url,params='Imageslim') r.raise_for_status () Contenter=r.content with open (path,'WB') as Filer:filer.write (Contenter) filer.close ()Print("The converted file {} has been saved to a local". Format (PATH)Else:        Print('Sorry, the format of your picture does not support slimming operation.')    #Main bodydefMain ():#fill in your AK and SKaccesskey = input ('Please enter your accesskey in seven Qiniu:') Secretkey= Input ('Please enter your Secretkey in seven Qiniu:')    #Identify identitieskeyq=Auth (Accesskey,secretkey)#The space you want to work withBucketname =input ("Please enter the name of the space (public) to be manipulated:")    #the outer-chain address of the space to be manipulatedUrlbucket = input ("Please enter the domain name or default outer link address that the space is bound to:")    #determining the type of Operation     while1: Order=input ('Please enter the action you need to take:') mode=order.split (' ') [0]ifmode = ='Conversion': Path=order.split (' ') [1] fname=path.split ('/') [-1:] [0]Print('you are trying to generate tokens .') upload (bucketname,path,fname,keyq,urlbucket)ifmode = ='Exit':            Print("you are welcome to use:")             BreakPrint("+----------------------------------------+")Print("| Welcome to the seven cow picture slimming feature |")Print("+----------------------------------------+")Print("| Notice of this procedure: |")Print("| | Seven cows can only slim images in JPG and png format |")Print("Accesskey,secretkey you need to provide services |")Print("|3. You need to provide bucket name and bucket outside the chain address. |")Print("+----------------------------------------+")Print("| How to use: |")Print("|. Slimming input format: Convert picture position (including suffix). |")Print(". Exit input format: Exit |")Print("+----------------------------------------+") Main ()

The program runs:

Picture compressed by the program: (approx. 22kb before compression)

Compressed Picture: (approx. 18kb after compression)

(vi) Error analysis

According to the official website, when an error occurs, the original image is returned.

(vii) Summary and expansion

Summary: This time to explore the seven Qiniu of the first api-picture slimming (Imageslim), this in our lives or applications can be benefited, and then in a few blog post I will continue to share the good seven Qiniu API and how to use.

Expansion: 1. In a folder there are many pictures under the circumstances can be traversed through the folder batch "slimming"

2. After uploading if the space is enough can also be used as a picture backup when the picture is mistakenly deleted can be restored in time

Application of Python in the Seven Cow Cloud Platform (ii) Image slimming

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.