TinyPNG is a website specialize in PNG and JPEG files compression technology. This is useful when your app or website host many images and you want to reduce the file size.

TinyPNG ‘s Python library is extremely easy to use. The only thing I wish the API can improve is the compression speed or being able to compress multiples images using threading or multiprocessing. Many large companies such as Samsung, Sony, Lego, Airbnb all use TinyPNG to compress the image files

Pricing

Images uploaded with API Price per unit
First 500 images per month free
Next 9,500 images $0.009
After 10,000 images $0.002

Suppose you compressed 1,000 images using the API, the first 500 images are free, and the remaining 500 images are charged at $0.009 per image, so you will pay $4.50 in the billing cycle.



Step 1. Sigh up for an account (get the API Key)

Sigh up link: https://tinypng.com/developers

Once you signed up for a TinyPNG account, you can locate your API key by logging into your account, and click API under Products section.

Step 2. Install tinify Python library

pip install --upgrade tinify



Step 3. Follow the tutorial

Source Code:

Check out Kite (free AI Coding Assistant) → Link

import os
import tinify

def compress_image(image_source, output_file_path):
    try:
        image_file_name = os.path.basename(image_source)
        
        if image_source.startswith('https'):
            source = tinify.from_url(image_source)
        else:
            source = tinify.from_file(image_source)
        print('{0} compressed successfully'.format(image_file_name))        
    except tinify.errors.AccountError:
        print('Invalid API Key')
        return False
    except tinify.errors.ConnectionError:
        print('Please check your internet connection')
        return False
    except tinify.errors.ClientError:
        print('File tpye is not supported')
        return False
    else:
        # export compressed image file
        source.to_file(output_file_path)
        print('File exported to {0}'.format(output_file_path))
        return True

image_folder = os.path.join(os.getcwd(), 'Images')
output_folder = os.path.join(os.getcwd(), 'Outputs')

file1 = os.path.join(image_folder, 'rocky.jpg')
file2 = os.path.join(image_folder, 'thumbnail.png')
file3 = 'https://live.staticflickr.com/2861/32837141013_3e8f61402b_o_d.jpg'

API_KEY = '<API KEY>'
tinify.key = API_KEY
compress_image(file1, os.path.join(output_folder, '1.jpeg'))
compress_image(file2, os.path.join(output_folder, '2.jpeg'))
compress_image(file3, os.path.join(output_folder, '3.jpeg'))