Image Optimize on the server side using TinyPNG's Web API

Overview

I decided to optimize the image in order to increase the display speed of the website currently in operation, but It's troublesome to clone and do it with jpgmini, and when I investigated whether it could be done on the server side, the famous TinyPNG said ** We have prepared a Web API **, so we will use it.

I was wondering if there was an article on qiita already, but it seems unlikely, so I will leave it as a memo.

1. Get the API KEY

When you go to TinyPNG's Developpers page, there is a field to enter your name and email address, so enter the data there. Then you will receive an email, so follow the link provided to get the API KEY.

2. Choose a client

TinyPNG includes ** REST API **, ** Ruby **, ** php **, ** node.js **, ** python **, ** java **, **. Net ** To use the API in your language I have a client. I use Python, so I will write this article in Python.

For Python, there is a client called tinify, so install it.

pip install tinify

This is the API explanation page. https://tinypng.com/developers/reference/python

3. Write code

With this client, you can Optimize with ** only 2 lines **.

source = tinify.from_file("unoptimized.jpg ")
source.to_file("optimized.jpg ")

only this. It feels like ** Simple is The BEST **, which is very nice.

By the way, before this, there is import of the client and registration of the API key.

import tinify
tinify.key = "Your API KEY"

3.1. Sample code

As a trial, I wrote the code to optimize the jpg or png file in the current directory (py2.7).

#!/usr/bin/env python
# coding: utf-8

import os
import sys
import tinify

TARGET_DIR = "."
tinify.key = "###################################"

def get_images():

    result = []
    files = os.listdir(".")

    for file in files:

        if file.endswith(".jpg ") or file.endswith(".png "):
                result.append(file)

    return result

def optimize(source, dest, target_dir):

    dest_path = os.path.join(target_dir, dest)

    if os.access(source, os.F_OK) != True:

        raise IOError("file not found: {}".format(source))

    optimizer = tinify.from_file(source)
    optimizer.to_file(dest_path)

    return


if __name__ == "__main__":

    images = get_images()

    # test optimize
    optimize(images[0], images[0], TARGET_DIR)

4. Precautions

Please note that TinyPNG seems to be able to upload only ** 500 ** images per month for free.

Recommended Posts

Image Optimize on the server side using TinyPNG's Web API
Notes on using matplotlib on the server
Publish the current directory on the web server
Drawing tips with matplotlib on the server side
Hit the Web API using requests Example: Flickr
Learning neural networks using Chainer-Creating a Web API server
Execute the command on the web server and display the result
I tried studying on the WEB server side at an in-house Python study session
Test.py is not reflected on the web server in Python3.
Build a web API server at explosive speed using hug
Try using the Twitter API
Try using the Twitter API
View the contents of the queue using the RabbitMQ Management Web API
Try using the PeeringDB 2.0 API
I tried using the COTOHA API (there is code on GitHub)
Proxy measures when using WEB API
Hit the web API in Python
I tried using the checkio API
Get the width of the div on the server side with Selenium + PhantomJS + Python
Try using the Python web framework Django (1)-From installation to server startup
Start the web server in the current directory
Category estimation using docomo's image recognition API
Try using the web application framework Flask
Try using the Kraken API in Python
Port forwarding your web server using iptables
I stumbled on the Hatena Keyword API
Tweet using the Twitter API in Python
Notes on using OpenCL on Linux on the RX6800
Download files on the web with Python
Create an application using the Spotify API
Build a web server on your Chromebook
Image segment using Oxford_iiit_pet on Google Colab
Image collection using Google Custom Search API
Add lines and text on the image
Play with puns using the COTOHA API
Record custom events using the Shotgun API
I tried using the BigQuery Storage API
I made a LINE BOT that returns a terrorist image using the Flickr API
Get the size of the image file on the web (Python3, no additional library required)
Image analysis was easy using the data and API provided by Microsoft COCO.