repl.it
@Scoder12/

image cut edit

Python

No description

fork
loading
Files
  • main.py
  • static
  • temp
  • templates
  • Packager files
  • poetry.lock
  • pyproject.toml
  • requirements.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import flask
from werkzeug.security import safe_join
from PIL import Image
import requests
import io
import json
import base64
import tempfile
import os

app = flask.Flask(__name__)

@app.route("/")
def index():
    return app.send_static_file('index.html')

@app.route("/img/<fname>")
def img(fname):
    return flask.send_from_directory("temp", fname)

@app.route('/<fname>/cut')
def cut(fname):
    if fname not in os.listdir('temp'):
        return "Image not found", 404
    return flask.render_template('cut.html', url="/img/"+fname)


def make_cuts(img, mode, cuts):
    width, height = img.size
    last = 0
    new = []
    if mode == 'x' and cuts[-1] < width:
        cuts.append(width)
    elif mode == 'y' and cuts[-1] < height:
        cuts.append(height)
    
    for pos in cuts:
        if mode == 'x':
            im = img.crop((last, 0, pos, height))
        elif mode == 'y':
            im = img.crop((0, last, width, pos))
        else:
            raise ValueError("Invalid mode")
        new.append(im)
        last = pos
    return new


def make_data_urls(imgs):
    outimgs = []
    for img in imgs:
        with io.BytesIO() as out:
            img.save(out, format="PNG")
            outimgs.append("data:image/png;base64,"+base64.b64encode(out.getvalue()).decode())
    return outimgs


@app.route('/<fname>/textedit')
def textedit(fname):
    ipath = safe_join('temp', fname)
    if fname is None:
        return "Invalid filename"
    data = flask.request.args or {}
    mode = data.get('mode')
    cuts = data.get('cuts')
    try:
        cuts = json.loads(cuts)
    except:
        return "Can't load cuts as JSON"
    if type(mode) != str or mode not in 'xy':
        return "Invalid mode"
    if type(cuts) != list or not all([type(i) is int for i in cuts]):
        return "Invalid cut data"
    try:
        img = Image.open(ipath)
    except:
        return "Image not found", 404
    if cuts:
        cuts = sorted(cuts)
        new = make_cuts(img, mode, cuts)
    else:
        new = [img]
    outimgs = make_data_urls(new)
    return flask.render_template("text.html", outimgs=outimgs, enumerate=enumerate)


@app.route("/loadimg", methods=["POST"])
def loadimg():
    args = flask.request.form or {}
    url = args.get("url")
    if not url:
        return "Invalid url"
    try:
        r = requests.get(url)#, stream=True)
        r.raise_for_status()
        with tempfile.NamedTemporaryFile(dir="./temp", delete=False) as f:
            #for chunk in r.iter_contents(size=8192):
            #    f.write(chunk)
            f.write(r.content)
            fname = f.name
    except Exception as e:
        print(f"Error loading url: {e.__class__.__name__}: {str(e)}")
        return "Error loading url"
    parts = fname.split("/")
    if parts[-2] != "temp":
        raise ValueError(f"Weird filename: {fname}")
    return flask.redirect("/"+parts[-1]+"/cut")

app.run('0.0.0.0', port=8080)
?