compress_db_img.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import sqlite3
  2. import io
  3. from PIL import Image
  4. # 连接到SQLite数据库
  5. conn = sqlite3.connect('/Users/alvin/memos_prod.db')
  6. cursor = conn.cursor()
  7. # 查询不是webp格式的图片数据
  8. cursor.execute("SELECT id, filename, `blob`, type, size FROM resource WHERE type like 'image%' AND type != 'image/webp'")
  9. # 获取查询结果的所有行
  10. rows = cursor.fetchall()
  11. # 遍历查询结果
  12. for row in rows:
  13. # 解析每一行的数据
  14. image_id = row[0]
  15. filename = row[1]
  16. blob = row[2]
  17. old_type = row[3]
  18. old_size = row[4]
  19. # 将BLOB数据转换为PIL Image对象
  20. image = Image.open(io.BytesIO(blob))
  21. # 创建一个新的内存缓冲区
  22. new_blob = io.BytesIO()
  23. # 将图片压缩为webp格式并保存到新的内存缓冲区
  24. image.save(new_blob, format='webp', quality=50)
  25. # 获取新的图片数据和相关信息
  26. new_blob_data = new_blob.getvalue()
  27. new_size = len(new_blob_data)
  28. new_filename = filename.rsplit('.', 1)[0] + '.webp'
  29. new_type = 'image/webp'
  30. # 日志打印
  31. print(f'{image_id}压缩前: {old_size}, 压缩后:{new_size}')
  32. # 更新数据库中的记录
  33. cursor.execute("UPDATE resource SET filename=?, blob=?, type=?, size=? WHERE id=?", (new_filename, new_blob_data, new_type, new_size, image_id))
  34. # 提交事务并关闭连接
  35. conn.commit()
  36. conn.close()