Skip to content

Commit

Permalink
Batch
Browse files Browse the repository at this point in the history
  • Loading branch information
tiritibambix committed Dec 19, 2024
1 parent e7dd07f commit d48d203
Show file tree
Hide file tree
Showing 3 changed files with 159 additions and 64 deletions.
138 changes: 77 additions & 61 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import subprocess
import requests
from werkzeug.utils import secure_filename
from zipfile import ZipFile
from PIL import Image

# Configuration
Expand Down Expand Up @@ -37,27 +38,32 @@ def get_image_dimensions(filepath):
def index():
return render_template('index.html')

# Téléchargement d'une image depuis l'ordinateur
# Téléchargement d'une ou plusieurs images depuis l'ordinateur
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
def upload_files():
if request.method == 'GET':
return redirect(url_for('index'))

if 'file' not in request.files:
flash('Aucun fichier sélectionné.')
return redirect(url_for('index'))

file = request.files['file']
if file.filename == '':
flash('Aucun fichier sélectionné.')
return redirect(url_for('index'))
files = request.files.getlist('file')
uploaded_files = []

for file in files:
if file.filename == '':
continue

if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
uploaded_files.append(filename)

if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
flash(f'Fichier {filename} uploadé avec succès.')
return redirect(url_for('resize_options', filename=filename))
if uploaded_files:
flash(f'{len(uploaded_files)} fichiers uploadés avec succès.')
return redirect(url_for('resize_options_batch', filenames=",".join(uploaded_files)))
else:
extensions = ', '.join(ALLOWED_EXTENSIONS)
flash(f"Format de fichier non supporté. Formats acceptés : {extensions}")
Expand Down Expand Up @@ -86,67 +92,77 @@ def upload_url():
flash(f'Échec du téléchargement : {str(e)}')
return redirect(url_for('index'))

# Page pour choisir les options de redimensionnement
@app.route('/resize_options/<filename>')
def resize_options(filename):
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
dimensions = get_image_dimensions(filepath)
if not dimensions:
flash("Impossible d'obtenir les dimensions de l'image.")
return redirect(url_for('index'))

width, height = dimensions
return render_template('resize.html', filename=filename, width=width, height=height)
# Page pour choisir les options de redimensionnement par lot
@app.route('/resize_options_batch/<filenames>')
def resize_options_batch(filenames):
filenames = filenames.split(',')
dimensions = {filename: get_image_dimensions(os.path.join(app.config['UPLOAD_FOLDER'], filename)) for filename in filenames}

# Redimensionner l'image
@app.route('/resize/<filename>', methods=['POST'])
def resize_image(filename):
for filename, dims in dimensions.items():
if not dims:
flash(f"Impossible d'obtenir les dimensions de l'image : {filename}")
return redirect(url_for('index'))

return render_template('resize_batch.html', filenames=filenames, dimensions=dimensions)

# Redimensionner les images par lot
@app.route('/resize_batch', methods=['POST'])
def resize_batch():
quality = request.form.get('quality', '100') # Valeur par défaut : 100%
format_conversion = request.form.get('format', None)
keep_ratio = 'keep_ratio' in request.form # Checkbox pour garder le ratio
keep_ratio = 'keep_ratio' in request.form
width = request.form.get('width', '')
height = request.form.get('height', '')
percentage = request.form.get('percentage', '')

filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
output_filename = filename
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)

if format_conversion:
output_filename = f"{os.path.splitext(filename)[0]}.{format_conversion.lower()}"
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
filenames = request.form.getlist('filenames')
output_zip_path = os.path.join(app.config['OUTPUT_FOLDER'], 'batch_output.zip')

try:
# Déterminer les options de redimensionnement
if width.isdigit() and height.isdigit():
resize_value = f"{width}x{height}" if not keep_ratio else f"{width}x{height}!"
elif percentage.isdigit() and 0 < int(percentage) <= 100:
resize_value = f"{percentage}%"
else:
flash('Veuillez spécifier soit des dimensions (width/height), soit un pourcentage valide.')
return redirect(url_for('resize_options', filename=filename))

# Commande ImageMagick
command = ["/usr/local/bin/magick", "convert", filepath]
command.extend(["-resize", resize_value])
if quality.isdigit() and 1 <= int(quality) <= 100:
command.extend(["-quality", quality])
command.extend(["-strip", output_path]) # Supprime les métadonnées inutiles
subprocess.run(command, check=True)

flash(f'L’image a été redimensionnée avec succès sous le nom {output_filename}.')
return redirect(url_for('download', filename=output_filename))
with ZipFile(output_zip_path, 'w') as zipf:
for filename in filenames:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
output_filename = filename
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)

if format_conversion:
output_filename = f"{os.path.splitext(filename)[0]}.{format_conversion.lower()}"
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)

# Déterminer les options de redimensionnement
if width.isdigit() and height.isdigit():
resize_value = f"{width}x{height}" if not keep_ratio else f"{width}x{height}!"
elif percentage.isdigit() and 0 < int(percentage) <= 100:
resize_value = f"{percentage}%"
else:
flash('Veuillez spécifier soit des dimensions (width/height), soit un pourcentage valide.')
return redirect(url_for('resize_options_batch', filenames=",".join(filenames)))

# Commande ImageMagick
command = ["/usr/local/bin/magick", "convert", filepath]
command.extend(["-resize", resize_value])
if quality.isdigit() and 1 <= int(quality) <= 100:
command.extend(["-quality", quality])
command.extend(["-strip", output_path]) # Supprime les métadonnées inutiles
subprocess.run(command, check=True)

# Ajouter au ZIP
zipf.write(output_path, arcname=output_filename)

flash('Images redimensionnées et compressées avec succès.')
return redirect(url_for('download_batch'))
except subprocess.CalledProcessError as e:
flash(f"Erreur lors du traitement de l'image : {e}")
return redirect(url_for('resize_options', filename=filename))
flash(f"Erreur lors du traitement des images : {e}")
return redirect(url_for('resize_options_batch', filenames=",".join(filenames)))
except Exception as e:
flash(f"Une erreur est survenue : {e}")
return redirect(url_for('resize_options', filename=filename))
return redirect(url_for('resize_options_batch', filenames=",".join(filenames)))

# Télécharger l'image redimensionnée
@app.route('/download/<filename>')
def download(filename):
return send_from_directory(app.config['OUTPUT_FOLDER'], filename, as_attachment=True)
# Télécharger le fichier ZIP contenant les images redimensionnées
@app.route('/download_batch')
def download_batch():
zip_path = os.path.join(app.config['OUTPUT_FOLDER'], 'batch_output.zip')
return send_from_directory(app.config['OUTPUT_FOLDER'], 'batch_output.zip', as_attachment=True)

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
app.run(host='0.0.0.0', port=5000)
10 changes: 7 additions & 3 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,20 @@
<body>
<div class="container">
<h1>ImageMagickSimpleGUI</h1>
<h2>Upload an image</h2>

<!-- Upload single or multiple images -->
<h2>Upload one or more images</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="file" name="file" multiple>
<button type="submit">Upload</button>
</form>

<!-- Upload via URL -->
<h2>Or provide an image URL</h2>
<form action="/upload_url" method="post">
<input type="text" name="url" placeholder="Enter image URL">
<button type="submit">Download and Upload</button>
</form>
</div>
</body>
</html>
</html>
75 changes: 75 additions & 0 deletions templates/resize_batch.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resize Batch Options</title>
<style>
:root {
/** Dark theme primary colors */
--clr-primary-a0: #808080;
--clr-primary-a10: #8d8d8d;
--clr-primary-a20: #9b9b9b;
--clr-primary-a30: #a9a9a9;
--clr-primary-a40: #b6b6b6;
--clr-primary-a50: #c5c5c5;

/** Dark theme surface colors */
--clr-surface-a0: #121212;
--clr-surface-a10: #282828;
--clr-surface-a20: #3f3f3f;
--clr-surface-a30: #575757;
--clr-surface-a40: #717171;
--clr-surface-a50: #8b8b8b;
}

body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: var(--clr-surface-a0);
color: var(--clr-primary-a50);
}
.container {
background-color: var(--clr-surface-a10);
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
text-align: center;
}
input, button, select {
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>Redimensionner plusieurs images</h1>
<form action="/resize_batch" method="post">
{% for filename in filenames %}
<input type="hidden" name="filenames" value="{{ filename }}">
{% endfor %}
<label>Width:</label> <input type="text" name="width">
<label>Height:</label> <input type="text" name="height">
<input type="checkbox" name="keep_ratio"> Keep Aspect Ratio
<br>
<label>Percentage:</label> <input type="text" name="percentage">
<br>
<label>Quality (1-100):</label> <input type="text" name="quality" value="100">
<br>
<label>Convert to format:</label>
<select name="format">
<option value="">Keep Original</option>
<option value="jpg">JPG</option>
<option value="png">PNG</option>
<option value="webp">WEBP</option>
</select>
<br>
<button type="submit">Apply Resize</button>
</form>
</div>
</body>
</html>

0 comments on commit d48d203

Please sign in to comment.