Skip to content

Commit

Permalink
trying out flask
Browse files Browse the repository at this point in the history
  • Loading branch information
rnddave committed May 14, 2024
1 parent fa2750f commit 56b6c3b
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 0 deletions.
75 changes: 75 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from flask import Flask, request, jsonify, send_from_directory, render_template
import os
import qrcode
from PIL import Image
import io
import base64

app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads/'
QR_FOLDER = 'static/qr-codes/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['QR_FOLDER'] = QR_FOLDER

# Ensure the upload and qr-codes directories exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(QR_FOLDER, exist_ok=True)

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

@app.route('/generate-qr', methods=['POST'])
def generate_qr():
url = request.form['url']
format = request.form['format']
logo = request.files['logo']

logo_path = os.path.join(app.config['UPLOAD_FOLDER'], logo.filename)
logo.save(logo_path)

# Create QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white').convert('RGB')

# Add logo to QR code
logo_img = Image.open(logo_path)
logo_img = logo_img.resize((50, 50))
pos = ((img.size[0] - logo_img.size[0]) // 2, (img.size[1] - logo_img.size[1]) // 2)
img.paste(logo_img, pos, logo_img)

# Save the QR code to the specified format
filename = f'qr_code.{format}'
file_path = os.path.join(app.config['QR_FOLDER'], filename)
if format == 'png':
img.save(file_path)
elif format == 'svg':
img.save(file_path, format='SVG')
elif format == 'pdf':
img.save(file_path, format='PDF')

# Create preview URL
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
preview_url = f"data:image/png;base64,{img_str}"

# Clean up uploaded logo
os.remove(logo_path)

return jsonify({
'previewUrl': preview_url,
'downloadUrl': f'/static/qr-codes/{filename}',
'filename': filename,
'format': format
})

if __name__ == '__main__':
app.run(debug=True)
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Flask
qrcode[pil]
Pillow
Empty file added static/qr-codes/readme.md
Empty file.
Empty file added static/uploads/readme.md
Empty file.
46 changes: 46 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
</head>
<body>
<h1>QR Code Generator</h1>
<form id="qr-form" action="/generate-qr" method="POST" enctype="multipart/form-data">
<label for="url">Target URL:</label>
<input type="text" id="url" name="url" required><br><br>
<label for="logo">Logo Image:</label>
<input type="file" id="logo" name="logo" accept="image/*" required><br><br>
<label for="format">Choose format:</label>
<select id="format" name="format" required>
<option value="png">PNG</option>
<option value="svg">SVG</option>
<option value="pdf">PDF</option>
</select><br><br>
<button type="submit">Generate QR Code</button>
</form>
<div id="qr-preview"></div>
<a id="download-link" style="display:none;">Download</a>

<script>
document.getElementById('qr-form').addEventListener('submit', async function(event) {
event.preventDefault();
const formData = new FormData(this);
const response = await fetch('/generate-qr', {
method: 'POST',
body: formData
});
const result = await response.json();
const qrPreview = document.getElementById('qr-preview');
qrPreview.innerHTML = `<img src="${result.previewUrl}" alt="QR Code Preview">`;

const downloadLink = document.getElementById('download-link');
downloadLink.style.display = 'block';
downloadLink.href = result.downloadUrl;
downloadLink.download = result.filename;
downloadLink.textContent = `Download as ${result.format}`;
});
</script>
</body>
</html>

0 comments on commit 56b6c3b

Please sign in to comment.