-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
122 lines (95 loc) · 4.14 KB
/
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
111
112
113
114
115
116
117
118
119
120
121
122
from flask import Flask, render_template, request, flash, redirect, url_for, send_file
from werkzeug.utils import secure_filename
from PIL import Image
from rembg import remove
import os
UPLOAD_FOLDER = "images"
DOWNLOAD_FOLDER = "converted_images"
ALLOWED_EXTENSIONS = {'jpg', 'png', 'webp', 'jfif', 'bmp', 'svg', 'avif'}
app = Flask(__name__)
app.config['SECRET_KEY'] = "secret_key_here"
app.config['TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/image_convert', methods=['GET', 'POST'])
def jpg_to_png_converter():
if request.method == "POST":
if 'file' not in request.files:
flash("No file part")
return redirect(url_for('image_convert_page'))
file = request.files['file']
if file.filename == "":
flash("File not selected")
return redirect(url_for("image_convert_page"))
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('converted_image', filename=filename))
return render_template('jpg_to_png.html')
@app.route('/converted_image/<filename>')
def converted_image(filename):
try:
image = Image.open(f"{app.config['UPLOAD_FOLDER']}/{filename}")
new_image_name = os.path.splitext(filename)[0] + "_png"
new_image_path = f"{app.config['DOWNLOAD_FOLDER']}/{new_image_name}.png"
if filename.lower().endswith(".svg"):
pass
elif filename.lower().endswith(".avif"):
pass
image.save(new_image_path)
# send_file
with open(new_image_path, 'rb') as bites:
response = send_file(
bites,
mimetype='image/png',
as_attachment=True,
download_name=f'{new_image_name}.png'
)
# delete original image
original_image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
if os.path.exists(original_image_path):
os.remove(original_image_path)
else:
app.logger.error("Error: %s file not found" % original_image_path)
# delete converted image
if os.path.exists(new_image_path):
os.remove(new_image_path)
else:
app.logger.error("Error: %s file not found" % new_image_path)
return response
except Exception as e:
app.logger.error("An error occurred: ", e)
return f"An error occurred: {e}"
@app.route('/remove_bg', methods=['GET', 'POST'])
def remove_image_bg():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(upload_path)
# Check if the file is not PNG, if so convert it to PNG first
if not filename.lower().endswith(".png"):
image = Image.open(upload_path)
filename = os.path.splitext(filename)[0] + ".png" # change the extension to .png
upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) # update upload_path
image.save(upload_path, "PNG")
input_img = Image.open(upload_path)
output = remove(input_img)
output_path = os.path.join(app.config['DOWNLOAD_FOLDER'], os.path.splitext(filename)[0] + "_nobg.png")
output.save(output_path, "PNG")
return send_file(output_path, as_attachment=True)
return render_template('bg_remover.html')
if __name__ == '__main__':
app.run(debug=True)