python动态规划图像压缩
时间: 2023-12-02 10:43:13 浏览: 26
以下是使用Python实现动态规划图像压缩的示例代码:
```python
import requests
from io import BytesIO
from PIL import Image
# 读取图片
img = Image.open('example.png')
# 将图片转换为字节流
img_byte_arr = BytesIO()
img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
# 发送POST请求到tinypng API
response = requests.post(
'https://api.tinify.com/shrink',
headers={
'Authorization': 'Basic ' + 'YOUR_API_KEY'.encode('base64').strip()
},
data=img_byte_arr
)
# 从响应中获取压缩后的图片
compressed_img_url = response.headers['Location']
compressed_img_response = requests.get(compressed_img_url)
compressed_img_byte_arr = BytesIO(compressed_img_response.content)
# 将压缩后的图片保存到本地
compressed_img = Image.open(compressed_img_byte_arr)
compressed_img.save('example_compressed.png')
```
需要注意的是,上述代码中的`YOUR_API_KEY`需要替换为你在tinypng官网上申请的API Key。