python图片压缩保存到mysql
时间: 2023-08-13 11:35:23 浏览: 47
首先,我们需要安装Pillow库用于图片处理和MySQLdb库用于连接MySQL数据库。在命令行中输入以下命令安装:
```
pip install pillow
pip install mysqlclient
```
然后,我们可以使用以下代码将图片压缩并保存到MySQL数据库中:
```python
from PIL import Image
import io
import MySQLdb
# 打开图片并压缩
image = Image.open('image.jpg')
image = image.resize((800, 600), resample=Image.LANCZOS)
# 将图片保存到内存中
with io.BytesIO() as output:
image.save(output, format='JPEG', quality=50)
content = output.getvalue()
# 连接MySQL数据库
conn = MySQLdb.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
# 插入图片数据
try:
with conn.cursor() as cursor:
sql = 'INSERT INTO images (content) VALUES (%s)'
cursor.execute(sql, (content,))
conn.commit()
except Exception as e:
print(e)
finally:
conn.close()
```
在上面的代码中,我们首先使用Pillow库打开原始图片并将其压缩到800x600。然后,我们使用BytesIO将压缩后的图片保存到内存中。最后,我们使用MySQLdb库连接到MySQL数据库并将图片数据插入到数据库中。
注意,我们在插入数据时使用了占位符来避免SQL注入攻击。我们还必须在最后关闭数据库连接。