backend: convert input images to webp
This commit is contained in:
parent
d786d7f7af
commit
4921d4bd6f
5 changed files with 32 additions and 7 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
@ -3,5 +3,5 @@ venv/
|
|||
__pycache__/
|
||||
.idea/
|
||||
.DS_Store
|
||||
vn_database.db
|
||||
screens/
|
||||
*.db
|
||||
store/
|
|
@ -4,6 +4,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||
from pathlib import Path
|
||||
|
||||
from vntypes import Novel, Mark
|
||||
from utils import *
|
||||
from db import VNDB
|
||||
|
||||
app = FastAPI()
|
||||
|
@ -42,7 +43,4 @@ async def novel_thumb(thumb: Annotated[bytes, File()], filename: str):
|
|||
|
||||
@app.post("/api/screenshot")
|
||||
async def screenshot(scrshot: Annotated[bytes, File()], filename: str):
|
||||
Path("screens/").mkdir(exist_ok=True)
|
||||
with open(Path("screens", filename), "wb") as file:
|
||||
file.write(scrshot)
|
||||
return {"file_size": len(scrshot)}
|
||||
return {"file_size": save_image(scrshot, "screens", filename)}
|
|
@ -1,8 +1,10 @@
|
|||
import sqlite3
|
||||
|
||||
from utils import asset
|
||||
|
||||
class VNDB:
|
||||
|
||||
def __init__(self, db_name='vn_database.db'):
|
||||
def __init__(self, db_name=asset('vn_database.db')):
|
||||
self.__db_name = db_name
|
||||
connection = sqlite3.connect(self.__db_name)
|
||||
cursor = connection.cursor()
|
||||
|
|
25
backend/utils.py
Normal file
25
backend/utils.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
from PIL import Image, UnidentifiedImageError
|
||||
from pathlib import Path
|
||||
import io
|
||||
|
||||
def asset(path: str) -> Path:
|
||||
return Path("store", path)
|
||||
|
||||
|
||||
def image_normalize(img: bytes) -> bytes:
|
||||
try:
|
||||
byte_arr = io.BytesIO()
|
||||
img = Image.open(io.BytesIO(img))
|
||||
img.save(byte_arr, format='WEBP')
|
||||
return byte_arr.getvalue()
|
||||
except UnidentifiedImageError:
|
||||
return 0
|
||||
|
||||
def save_image(img: bytes, dir: str, name: str) -> int:
|
||||
path = asset(dir)
|
||||
path.mkdir(exist_ok=True)
|
||||
img = image_normalize(img)
|
||||
if img:
|
||||
with open(Path(path, name+'.webp'), "wb") as file:
|
||||
file.write(img)
|
||||
return len(img)
|
Loading…
Add table
Add a link
Reference in a new issue