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.
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.
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
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"
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)
Please note that TinyPNG seems to be able to upload only ** 500 ** images per month for free.
Recommended Posts