Python(16줄)과 TinyPNG API로 이미지 압축

7751 단어 apipythonimage

TinyPNG가 무엇인가요?



https://tinypng.com/

TinyPNG uses smart lossy compression techniques to reduce the file size of your WEBP, JPEG and PNG files. By selectively decreasing the number of colors in the image, fewer bytes are required to store the data. The effect is nearly invisible but it makes a very large difference in file size!



TinyPNG에는 이미지를 압축할 수 있는 웹 앱이 있습니다(최대 20개 이미지 및 각각 최대 5MB). 이는 유용하지만 때때로 20개 이상의 이미지를 압축해야 합니다.

가장 좋은 점은 TinyPNG에 여러 언어에 대한 API와 패키지가 있다는 것입니다.

TinyPNG 개발자 API
https://tinypng.com/developers

이번 포스팅에서는 파이썬으로 API를 사용하는 방법을 보여드리겠습니다.

1 단계. API 키 받기
2 단계. 핍 패키지 설치
3단계. 스크립트 작성(20줄 미만)
4단계. 스크립트 실행

1 단계. API 키 받기



https://tinypng.com/developers로 이동하여 이름과 이메일 주소를 입력합니다. API 키를 쉽게 얻을 수 있습니다.

API는 최대 500개의 요청까지 무료입니다.

2 단계. 핍 패키지 설치



pip install tinify

3단계. 스크립트 작성



시도를 제외하고 추가하는 것이 좋습니다 😜

심판 https://tinypng.com/developers/reference/python

스크립트는 매우 간단합니다. 소스 이미지에 대해 src를 생성하고 최적화된 이미지에 대해 dist를 생성합니다.glob로 파일 이름을 가져오고 이미지 파일을 tinify.from_file 메서드로 TinyPng API에 전달합니다.
이미지 파일 경로 대신 이미지 파일을 버퍼 또는 이미지 URL로 전달할 수 있습니다.

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



source = tinify.from_url("https://tinypng.com/images/panda-happy.png")
source.to_file("optimized.png")
app.py
import tinify
from glob import glob
import os.path
tinify.key = "your_api_key"
source_dir_name = 'src'
destination_dir_name = 'dist'
# get all files names in directory
files = glob(source_dir_name + '/*')
# compress all files
for file in files:
    print('compressing ' + file)
    source = tinify.from_file(file)
    file_name, ext = os.path.splitext(file)
    file_name = file_name.replace(source_dir_name + '/', '')
    source.to_file(destination_dir_name + "/" + file_name + ".png")
print('compressed all images')

4단계. 스크립트 실행



스크립트를 실행하기 전에 2개의 작은 것이 필요합니다.
먼저 두 개의 디렉토리(src 및 dist)를 만듭니다. 이 dir 이름이 마음에 들지 않으면 원하는 대로 변경할 수 있습니다.

$ mkdir src dist

그런 다음 압축하려는 동영상 파일을 src dir.

거의 다 왔어!

마지막으로 스크립트를 실행하십시오!

$ python app.py
compressing src/MoreToggles.css.png
compressing src/CSSscrolshadows.jpg
compressing src/CSStoTailwindCSS.png
compressing src/broider.png
compressing src/Tailblocks.jpg
compressing src/calcolor.jpg
compressing src/screenshot-rocks.png
compressing src/SmoothShadow.png
compressing src/Neumorphism.io.png
compressed all images

레포


누룩 / tinypng_image_compress


tinypng api를 사용한 이미지 압축 스크립트





tinypng_image_compress


tinypng api를 사용한 이미지 압축 스크립트

사용하는 방법


$ git clone https://github.com/koji/tinypng_image_compress.git
$ cd tinypng_image_compress

# move images to `src` folder

$ python app.py

이미지 압축
이미지 크기 조정

View on GitHub


일반적으로 이미지 파일 크기의 20~50%를 줄일 수 있습니다.

더 많은 기능을 쉽게 사용하고 싶다면 이 글을 확인하는 것을 추천합니다.

https://medium.com/acronis-design/how-to-optimize-images-by-using-macos-terminal-tinypng-cli-dd0bb8e67708

좋은 웹페이지 즐겨찾기