Python 3 TinyPNG + TinyJPG API Tutorial to Compress PNG and JPEG Images to Small Size Using tinify Module Full Project For Beginners

Python 3 TinyPNG + TinyJPG API Tutorial to Compress PNG and JPEG Images to Small Size Using tinify Module Full Project For Beginners

 

Welcome folks today in this tutorial we will be compressing jpg and png images using tinypng and tinyjpg api in python 3. All the full source code of the application will be shown below

 

 

 

Get Started

 

 

 

In order to get started you need to go to official website of tinypng to get free api key as shown here

 

 

 

 

 

 

And now after getting the api key you need to create a new python project in the empty directory and issue the pip command

 

pip install tinify

After installing this library make an app.py file and copy paste the following code into it

 

app.py

 

import tinify
tinify.key = "YOUR_API_KEY"

source = tinify.from_file("profile.png")
source.to_file("optimizedimage.png")

 

 

As you can see we are importing the library at the very first line of code and then we are setting the api_key of your project simply copy paste it from your dashboard and then we are taking the input image and compressing it

See also  Python 3 Script to Transfer Large Images & PDF Documents From Remote Server Using Socket Full Project For Beginners

 

If you run your python project by typing the below command

 

python app.py

 

As you can see it has compressed a 1.89MB image to 368KB optimized and compressed image as shown below

 

 

 

 

 

 

You can also compress jpg images as well by python module just change or modify the above snippet of code like this as shown below

 

 

import tinify
tinify.key = "YOUR_API_KEY"

source = tinify.from_file("profile.jpg")
source.to_file("optimizedimage.jpg")

 

 

You can also upload an image from a buffer (a string with binary) and get the compressed image data.

 

with open("unoptimized.jpg", 'rb') as source:
    source_data = source.read()
    result_data = tinify.from_buffer(source_data).to_buffer()

 

 

See also  Python 3 Bing API Wallpaper Downloader Web Scraping Script Using BeautifulSoup4 Full Project For Beginners

You can provide a URL to your image instead of having to upload it.

 

source = tinify.from_url("https://tinypng.com/images/panda-happy.png")
source.to_file("optimized.jpg")

 

Leave a Reply