Website image generator working

This commit is contained in:
TT-392 2024-09-14 20:49:57 +02:00
parent 2a81b7efde
commit 0accf4dc96
8 changed files with 220 additions and 14 deletions

View file

@ -1,18 +1,26 @@
from flask import Flask, render_template, request, redirect, url_for
from flask import Flask, render_template, request, redirect, url_for, session
from PIL import Image
from gen_image import gen_image
from printer_info import *
from datetime import datetime
import os
valid_height=800
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['TEXT_FOLDER'] = 'static/text'
app.secret_key = "blahaj"
# Ensure the upload directory exists
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
if not os.path.exists(app.config['TEXT_FOLDER']):
os.makedirs(app.config['TEXT_FOLDER'])
@app.route('/', methods=['GET', 'POST'])
def upload_image():
@app.route('/image', methods=['GET', 'POST'])
def image():
if request.method == 'POST':
if 'image' not in request.files:
return redirect(request.url)
@ -35,12 +43,109 @@ def upload_image():
#################
return render_template('image.html', filename="upload"+extension, height=height, valid=valid)
return render_template('image.html', filename=None)
return render_template('image.html')
templates = {
"DNH": {
"text1": {
"string": "Do Not Hack",
"size": 50,
"pos": 0
},
"text2": {
"string": "bottom text",
"size": 25,
"pos": 55
},
"cut": True
},
"Food": {
"text1": {
"string": "Nickname",
"size": 50,
"pos": 0
},
"text2": {
"string": "",
"size": 25,
"pos": 55
},
"cut": True
}
}
@app.route('/text-template', methods=['GET', 'POST'])
def text_template():
if request.method == 'POST':
template = templates[request.form["template"]]
if request.form["template"] == "Food":
template["text2"]["string"] = datetime.now().strftime('%Y-%m-%d')
session["text1"] = template["text1"]
session["text2"] = template["text2"]
session["cut"] = template["cut"]
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
@app.route('/text-form', methods=['GET', 'POST'])
def text_form():
if request.method == 'POST':
session["text1"] = {
"string": request.form["string1"],
"size": int(request.form["size1"]),
"pos": int(request.form["pos1"]),
}
session["text2"] = {
"string": request.form["string2"],
"size": int(request.form["size2"]),
"pos": int(request.form["pos2"]),
}
img = gen_image(label_width, session["text1"], session["text2"])
filepath = os.path.join(app.config['TEXT_FOLDER'], "text.png")
img.save(filepath)
print(session)
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
@app.route('/text', methods=['GET', 'POST'])
def text():
session["text1"] = templates["DNH"]["text1"]
session["text2"] = templates["DNH"]["text2"]
session["cut"] = templates["DNH"]["cut"]
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
@app.route('/text-print', methods=['GET', 'POST'])
def tex_print():
if request.method == 'POST':
if 'cut' in request.form:
print("printing and cutting")
session["cut"] = True;
else:
print("printing")
session["cut"] = False;
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
return render_template('text.html', filename="text.png", text1=session["text1"], text2=session["text2"], cut=session["cut"])
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return redirect(url_for('static', filename='uploads/' + filename))
@app.route('/text/<filename>')
def generated_file(filename):
return redirect(url_for('static', filename='text/' + filename))
if __name__ == "__main__":
app.run(debug=True)

12
flask/format_image.py Normal file
View file

@ -0,0 +1,12 @@
from PIL import Image
def format_image(path):
image = Image.open(path)
image = image.rotate(-90, expand=True)
new_image = Image.new('1', (512, image.height), 1)
new_image.paste(image, (0, 0))
return new_image
format_image("static/text/text.png")

View file

@ -2,12 +2,12 @@ from PIL import Image, ImageDraw, ImageFont
from colorama import Fore, Style
from printer_info import *
def gen_image(height, string1, string1_size, string1_pos, string2, string2_size, string2_pos, justification):
font1 = ImageFont.truetype("ComicMono.ttf", size=string1_size)
font2 = ImageFont.truetype("ComicMono.ttf", size=string2_size)
def gen_image(height, text1, text2):
font1 = ImageFont.truetype("ComicMono.ttf", size=text1["size"])
font2 = ImageFont.truetype("ComicMono.ttf", size=text2["size"])
text1_box = font1.getbbox(string1)
text2_box = font2.getbbox(string2)
text1_box = font1.getbbox(text1["string"])
text2_box = font2.getbbox(text2["string"])
text1_width = text1_box[2]
text2_width = text2_box[2]
@ -17,14 +17,26 @@ def gen_image(height, string1, string1_size, string1_pos, string2, string2_size,
if (text1_box[0] != 0 or text2_box[0] != 0):
print(Fore.YELLOW + "Warning, found situation where left corner of bbox of text != 0,", "text1_box:", text1_box, "text2_box", text2_box)
img = Image.new('1', (max(text1_width, text2_width), height), color=1)
# the 1 here assures we don't get a 0 width image
img = Image.new('1', (max(text1_width, text2_width, 1), height), color=1)
draw = ImageDraw.Draw(img)
draw.text((0, string1_pos), string1, font=font1)
draw.text((0, string2_pos), string2, font=font2)
draw.text((0, text1["pos"]), text1["string"], font=font1)
draw.text((0, text2["pos"]), text2["string"], font=font2)
return img
gen_image(label_width, "faf", 30, 10, "Hello world", 20, 40, justification="left").save('output.png')
Text1 = {
"string": "Hello world",
"size": 30,
"pos": 10,
}
Text2 = {
"string": "Hello worhfeiheifhefld",
"size": 20,
"pos": 40,
}
gen_image(label_width, Text1, Text2).save('output.png')

BIN
flask/output.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 636 B

23
flask/print.py Normal file
View file

@ -0,0 +1,23 @@
dev_path="/dev/usb/lp0"
def print_text(stream, text):
stream.write(text.encode('utf-8'))
def cut_paper(stream):
stream.write(b'\x1DVA\xc8')
def print_image(image):
buffer = io.BytesIO()
image.save(buffer, format='PBM')
pbm_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
stream = open('/dev/usb/lp0', 'wb')
print_text(stream, "test\n")
cut_paper(stream)
stream.close()

View file

@ -18,6 +18,9 @@
}
</style>
{% block head %}
{% endblock %}
</head>
<body>
<div class="container">

View file

@ -6,6 +6,7 @@
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
{% if filename %}
<h2>Uploaded Image:</h2>
<img src="{{ url_for('uploaded_file', filename=filename) }}" alt="Uploaded Image" style="max-width:300px;">

50
flask/templates/text.html Normal file
View file

@ -0,0 +1,50 @@
{% extends "base.html" %}
{% block content %}
<form method="POST" action="/text-template">
<label for="template">Template:</label>
<select name="template">
<option value="DNH">Do not hack</option>
<option value="Food">Food</option>
</select>
<input type="submit" value="Apply">
</form>
<form method="POST" action="/text-form">
<h2>String 1</h2>
Text:</span> <input type="text" value="{{text1["string"]}}" name="string1"><br>
Size: <input type="number" value="{{text1["size"]}}" name="size1" min="0" required
style="width: 40px"><br>
Y position: <input type="number" value="{{text1["pos"]}}" name="pos1" required
style="width: 40px"><br>
<h2>String 2</h2>
Text: <input type="text" value="{{text2["string"]}}" name="string2"><br>
Size: <input type="number" value="{{text2["size"]}}" name="size2" min="0" required
style="width: 40px"><br>
Y position: <input type="number" value="{{text2["pos"]}}" name="pos2" required
style="width: 40px"><br>
<input type="submit" value="Submit">
</form>
{% if filename %}
<br><br>
<img style="border: 1px solid blueviolet;"
src="{{ url_for('generated_file', filename=filename) }}" alt="Uploaded Image">
<form method="POST" action="/text-print">
{% if cut %}
<input type="checkbox" name="cut" value="cut" checked>
{%else %}
<input type="checkbox" name="cut" value="cut">
{%endif%}
<label for="cut"> Cut paper after printing </label><br>
<input type="submit" value="Print">
</form>
{% endif %}
{% endblock %}