Create an image compositing application using Flask. Install the Pillow module.
Select the image to be combined from the form, and select the file you want to combine, such as the logo. A composite image is displayed in the execution result. This time, the following two images are combined.
As usual, it's a peach again.
The name will be overwritten at the time of compositing, but please do something about it.
imgadd.py
import os
from PIL import Image
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
from werkzeug import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['jpg','png','gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = os.urandom(24)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('img.html')
@app.route('/show_img', methods=['GET', 'POST'])
def show_img():
if request.method == 'POST':
img_data = request.files['img_data']
logo_data = request.files['logo_data']
if img_data and allowed_file(img_data.filename):
filename = secure_filename(img_data.filename)
img_data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
SQUARE_FIT_SIZE = 600
MAIN_FILENAME = 'uploads/' + filename
im = Image.open(MAIN_FILENAME)
im.thumbnail((SQUARE_FIT_SIZE, SQUARE_FIT_SIZE))
width, height = im.size
if logo_data and allowed_file(logo_data.filename):
filename = secure_filename(logo_data.filename)
logo_data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
SQUARE_FIT_SIZE = 100
LOGO_FILENAME = 'uploads/' + filename
logo_im = Image.open(LOGO_FILENAME)
logo_width, logo_height = logo_im.size
im.paste(logo_im, (width-logo_width, height-logo_height), logo_im)
im.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
img_url = '/uploads/' + filename
return render_template('img.html', img_url=img_url)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.debug = True
app.run()
img.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="{{ url_for('show_img') }}" enctype="multipart/form-data">
Select the main image<input type="file" id="img_data" name="img_data">
Select logo<input type="file" id="logo_data" name="logo_data">
<input type="submit" value="Send">
</fomr>
<div>
{% if img_url %}
<p><img src="{{ img_url }}"></p>
{% endif %}
</div>
{% endblock %}
It's a simple form, but I'll send you an image right away.
Successful.