summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDebulois Quentin <quentin.debulois@gmail.com>2020-09-20 16:18:18 +0200
committerDebulois Quentin <quentin.debulois@gmail.com>2020-09-20 16:18:18 +0200
commit79e091c7c3796e6a4fd35ffb5b54b9e626954caa (patch)
treed651f9142a52f1e2ea8caa2ff7904bbb09c10bd2
parentdd8d8cbdd2394a487e9dc4badf8798d2b9df374a (diff)
Enfin POO OK.
-rw-r--r--.gitignore2
-rw-r--r--Redim/config.py49
-rw-r--r--Redim/convertisseur.py91
-rw-r--r--Redim/core.py140
-rw-r--r--Redim/main.py148
-rw-r--r--Redim/ui.py123
-rw-r--r--redim.spec (renamed from Redim.spec)0
7 files changed, 314 insertions, 239 deletions
diff --git a/.gitignore b/.gitignore
index db6559f..12f03ac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,7 +4,7 @@ Lib
Build
Dist
Test
-TEST
Cpp
Redim/__pycache__
+Redim/config
pyvenv.cfg
diff --git a/Redim/config.py b/Redim/config.py
index de03ead..c6a6070 100644
--- a/Redim/config.py
+++ b/Redim/config.py
@@ -1,19 +1,50 @@
-import json
+from sys import platform
+from os import mkdir, listdir, environ, getenv
+from os.path import isdir, join, getmtime, isfile
from time import time
from shutil import rmtree
-from os import mkdir, listdir, environ
-from os.path import isdir, join, getmtime
+import json
class Config():
- def sauvegarde(self, json_path, configuration):
- if not isdir(json_path):
- mkdir(json_path)
- with open(join(json_path, "config_redim"), "w") as f:
+ def __init__(self):
+ self._base_configuration = {
+ "dimensions": [[500, 350], [900, 900]],
+ "background": [255, 255, 255],
+ "format_final": ".webp",
+ "formats_acceptes": (
+ "jpg",
+ "jpeg",
+ "png",
+ "bmp",
+ "gif",
+ "webp"
+ )
+ }
+ if platform != "linux":
+ self.json_path = join(
+ getenv("USERPROFILE"),
+ "AppData",
+ "Local",
+ "Redim"
+ )
+ else:
+ self.json_path = "."
+ if platform != "linux":
+ self.nettoyage_pyinstaller()
+
+ def sauvegarde(self, configuration):
+ if not isdir(self.json_path):
+ mkdir(self.json_path)
+ with open(join(self.json_path, "config"), "w") as f:
json.dump(configuration, f)
+ print("\n[-] Modification enregistree.")
- def lecture(self, json_path):
- with open(join(json_path, "config_redim"), "r") as f:
+ def lecture(self):
+ if not isfile(join(self.json_path, "config")):
+ self.sauvegarde(self._base_configuration)
+ return self._base_configuration
+ with open(join(self.json_path, "config"), "r") as f:
configuration = json.load(f)
return configuration
diff --git a/Redim/convertisseur.py b/Redim/convertisseur.py
deleted file mode 100644
index ddb0092..0000000
--- a/Redim/convertisseur.py
+++ /dev/null
@@ -1,91 +0,0 @@
-from PIL.Image import ANTIALIAS
-from PIL.Image import new as image_new
-from PIL.Image import open as image_open
-from os import mkdir, listdir
-from os.path import isfile, isdir, join
-
-
-class Redim():
- def __init__(self, formats_acceptes):
- self.formats_acceptes = formats_acceptes
-
- def start(self, dossier, larg, haut, background_color, format_final):
- print("\n[-] travail pour", larg, "x", haut, "px :")
- if dossier == "":
- print(" >>>ERREUR<<< : Aucun dossier selectionne.")
- return
- if isdir(dossier):
- liste_fichier, dossier_sauvegarde = self.listage_fichiers_et_dossiers(dossier, larg)
- self.main(liste_fichier, dossier_sauvegarde, larg, haut, background_color, format_final)
- else:
- print(" >>>ERREUR<<< : Le dossier n'existe plus.")
-
- def listage_fichiers_et_dossiers(self, dossier, larg):
- liste_fichier = []
- dossier_sauvegarde = join(dossier, str(larg))
- if not isdir(dossier_sauvegarde):
- mkdir(dossier_sauvegarde)
- for nom in listdir(dossier):
- if isfile(join(dossier, nom)):
- if join(dossier, nom).rsplit(".", 1)[-1] in self.formats_acceptes:
- liste_fichier.append([join(dossier, nom), nom])
- return liste_fichier, dossier_sauvegarde
-
- def suppression_de_alpha(self, img, background_color):
- img = img.convert("RGBA")
- if img.mode in ("RGBA", "LA"):
- fond = image_new(img.mode[:-1], img.size, background_color)
- fond.paste(img, img.split()[-1])
- img = fond
- img.convert("RGB")
- return img
-
- def redimensionnement(self, img, larg, haut):
- if (img.size[0] >= larg) or (img.size[1] >= haut):
- img.thumbnail((larg, haut), ANTIALIAS)
- elif (img.size[0] / img.size[1]) <= (larg / haut):
- nouvelle_larg = int(haut * img.size[0] / img.size[1])
- img = img.resize((nouvelle_larg, haut), ANTIALIAS)
- else:
- nouvelle_haut = int(larg * img.size[1] / img.size[0] )
- img = img.resize((larg, nouvelle_haut), ANTIALIAS)
- return img
-
- def rennomage(self, origine_nom, larg, format_final):
- charcters_indesirable = ("(", ")", "[", "]", "{", "}","'", "#",
- "&","$","£", "¤", "€", "`", "^", "°", "¨",
- "@", "!", ",", "~", "%", ";", "µ", "§")
- charcters_underscore = (" ", "-")
- nouveau_nom = origine_nom
- for i in charcters_indesirable:
- nouveau_nom = nouveau_nom.replace(i, "")
- for i in charcters_underscore:
- nouveau_nom = nouveau_nom.replace(i, "_")
- return nouveau_nom.lower() + "_modif_" + str(larg) + format_final
-
- def main(self, liste_fichier, dossier_sauvegarde, larg, haut, background_color, format_final):
- for nom in liste_fichier:
- try:
- print(" [+] Travail sur :", nom[1])
- img = image_open(nom[0])
- print(" >> Taille initiale :", img.size[0] ,"x" ,img.size[1], "px")
- if nom[1].rsplit(".", 1)[-1] in ("png", "webp"):
- img = self.suppression_de_alpha(img, background_color)
- img = self.redimensionnement(img, larg, haut)
- print(" >> Taille apres redimensionnement :", img.size[0] ,"x" ,img.size[1], "px")
- nouveau_nom = self.rennomage(nom[1].rsplit(".", 1)[0], larg, format_final)
- fond = image_new("RGB", (larg, haut), background_color)
- fond.paste(img, ((larg - img.size[0]) // 2, (haut - img.size[1]) // 2))
- if isfile(join(dossier_sauvegarde, nouveau_nom)):
- adverbes_multplicatifs = ("_bis", "_ter", "_quater", "_quinquies", "_sexies", "_septies")
- nom_deja_present = nouveau_nom
- iteration = 0
- while isfile(join(dossier_sauvegarde, nom_deja_present)):
- nom_deja_present = nouveau_nom.rsplit(".", 1)[0] + adverbes_multplicatifs[iteration]
- nom_deja_present += format_final
- iteration += 1
- fond.save(join(dossier_sauvegarde, nom_deja_present))
- else:
- fond.save(join(dossier_sauvegarde, nouveau_nom))
- except Exception as e:
- print(" >>>ERREUR<<< : ", e)
diff --git a/Redim/core.py b/Redim/core.py
new file mode 100644
index 0000000..03d7f1c
--- /dev/null
+++ b/Redim/core.py
@@ -0,0 +1,140 @@
+from os import mkdir, listdir
+from os.path import isfile, isdir, join
+from PIL.Image import ANTIALIAS
+from PIL.Image import new as image_new
+from PIL.Image import open as image_open
+
+
+class Redim():
+ def __init__(self):
+ self.__charcters_indesirable = (
+ "(", ")", "[", "]", "{", "}", "'", "#", "¨",
+ "&", "$", "£", "¤", "€", "`", "^", "°", "§",
+ "@", "!", ",", "~", "%", ";", "µ"
+ )
+ self.__charcters_underscore = (" ", "-")
+ self.__adverbes_multplicatifs = (
+ "_bis", "_ter", "_quater", "_quinquies",
+ "_sexies", "_septies"
+ )
+
+ def start(self, dossier, configuration):
+ for i in range(len(configuration["dimensions"])):
+ print(
+ "\n[-] travail pour",
+ str(configuration["dimensions"][i][0]),
+ "x",
+ str(configuration["dimensions"][i][1]),
+ "px :"
+ )
+ if dossier != "":
+ if isdir(dossier):
+ liste, destination = self.listage(
+ dossier,
+ str(configuration["dimensions"][i][0]),
+ configuration["formats_acceptes"]
+ )
+ self.main(liste, destination, configuration, i)
+ else:
+ print(" >>>ERREUR<<< : Le dossier n'existe plus.")
+ else:
+ print(" >>>ERREUR<<< : Aucun dossier selectionne.")
+
+ def listage(self, dossier, larg, formats_acceptes):
+ liste = []
+ destination = join(dossier, str(larg))
+ if not isdir(destination):
+ mkdir(destination)
+ for nom in listdir(dossier):
+ if isfile(join(dossier, nom)):
+ if join(dossier, nom).rsplit(".", 1)[-1] in formats_acceptes:
+ liste.append([join(dossier, nom), nom])
+ return liste, destination
+
+ def suppression_de_alpha(self, img, background):
+ img = img.convert("RGBA")
+ if img.mode in ("RGBA", "LA"):
+ fond = image_new(img.mode[:-1], img.size, background)
+ fond.paste(img, img.split()[-1])
+ img = fond
+ img.convert("RGB")
+ return img
+
+ def redimensionnement(self, img, larg, haut):
+ if (img.size[0] >= larg) or (img.size[1] >= haut):
+ img.thumbnail((larg, haut), ANTIALIAS)
+ elif (img.size[0] / img.size[1]) <= (larg / haut):
+ nouvelle_larg = int(haut * img.size[0] / img.size[1])
+ img = img.resize((nouvelle_larg, haut), ANTIALIAS)
+ else:
+ nouvelle_haut = int(larg * img.size[1] / img.size[0])
+ img = img.resize((larg, nouvelle_haut), ANTIALIAS)
+ return img
+
+ def rennomage(self, origine_nom, larg, format_final):
+ nouveau_nom = origine_nom
+ for i in self.__charcters_indesirable:
+ nouveau_nom = nouveau_nom.replace(i, "")
+ for i in self.__charcters_underscore:
+ nouveau_nom = nouveau_nom.replace(i, "_")
+ return nouveau_nom.lower() + "_modif_" + str(larg) + format_final
+
+ def main(self, liste, destination, configuration, loop):
+ for nom in liste:
+ print(" [+] Travail sur :", nom[1])
+ img = image_open(nom[0])
+ print(
+ " >> Taille initiale :",
+ img.size[0],
+ "x",
+ img.size[1],
+ "px"
+ )
+ if nom[1].rsplit(".", 1)[-1] in ("png", "webp"):
+ img = self.suppression_de_alpha(
+ img,
+ configuration["background"]
+ )
+ img = self.redimensionnement(
+ img,
+ configuration["dimensions"][loop][0],
+ configuration["dimensions"][loop][1],
+ )
+ print(
+ " >> Taille apres redimensionnement :",
+ img.size[0],
+ "x",
+ img.size[1],
+ "px"
+ )
+ nouveau_nom = self.rennomage(
+ nom[1].rsplit(".", 1)[0],
+ configuration["dimensions"][loop][0],
+ configuration["format_final"]
+ )
+ fond = image_new(
+ "RGB",
+ (
+ configuration["dimensions"][loop][0],
+ configuration["dimensions"][loop][1]
+ ),
+ tuple(configuration["background"])
+ )
+ fond.paste(
+ img,
+ (
+ (configuration["dimensions"][loop][0] - img.size[0]) // 2,
+ (configuration["dimensions"][loop][1] - img.size[1]) // 2
+ )
+ )
+ if isfile(join(destination, nouveau_nom)):
+ nom_deja_present = nouveau_nom
+ iteration = 0
+ while isfile(join(destination, nom_deja_present)):
+ nom_deja_present = nouveau_nom.rsplit(".", 1)[0]\
+ + self.__adverbes_multplicatifs[iteration]
+ nom_deja_present += configuration["format_final"]
+ iteration += 1
+ fond.save(join(destination, nom_deja_present))
+ else:
+ fond.save(join(destination, nouveau_nom))
diff --git a/Redim/main.py b/Redim/main.py
index 32ad287..31318e9 100644
--- a/Redim/main.py
+++ b/Redim/main.py
@@ -1,153 +1,75 @@
-#!/usr/bin/python
-
-from os import system, listdir, environ, getenv
-from os.path import join, isfile, isdir, getmtime
-from sys import platform, exit
-from time import time
-from shutil import rmtree
-from PyQt5.QtWidgets import QFileDialog, QApplication, QWidget
+from sys import exit
+from PyQt5.QtWidgets import QFileDialog, QWidget, QApplication
from ui import Ui
+from core import Redim
from config import Config
-from convertisseur import Redim
-
def main():
- configuration = {
- "largeur1": 500,
- "hauteur1": 350,
- "largeur2": 900,
- "hauteur2": 900,
- "background_color": [255, 255, 255],
- "format_final": ".webp"
- }
- formats_acceptes = ("jpg", "jpeg", "png", "bmp", "gif", "webp")
-
- if platform != "linux":
- json_path = join(getenv("USERPROFILE"), "AppData", "Local", "Redim")
- else:
- json_path = "."
-
app = QApplication([])
widget = QWidget()
config = Config()
-
+ redim = Redim()
while True:
- redim = Redim(formats_acceptes)
- ui = Ui(configuration, formats_acceptes)
- if not isfile(join(json_path, "config_redim")):
- config.sauvegarde(json_path, configuration)
- else:
- print(json_path)
- configuration = config.lecture(json_path)
- if platform != "linux":
- config.nettoyage_pyinstaller()
+ configuration = config.lecture()
+ ui = Ui(configuration)
+ ui.reset_screen()
ui.affichage_banner()
ui.affichage_menu()
- choix = input("[>] Choix (numero) : ")
-
+ choix = input(
+ "[>] Choix (numero) : "
+ )
while True:
ui.reset_screen()
ui.affichage_banner()
-
if choix.strip() == "1":
dossier = QFileDialog.getExistingDirectory(
- widget,
- "Dossier a travailler."
- )
- redim.start(dossier, configuration["largeur1"], configuration["hauteur1"],
- tuple(configuration["background_color"]), configuration["format_final"])
- redim.start(dossier, configuration["largeur2"], configuration["hauteur2"],
- tuple(configuration["background_color"]), configuration["format_final"])
+ widget,
+ "Sélectionner le dossier sur lequel travailler."
+ )
+ redim.start(dossier, configuration)
ui.affichage_fin()
break
elif choix.strip() == "5":
ui.reset_screen()
- dimensions = [0, 0, 0, 0]
- for pos, i in enumerate(dimensions):
- if pos == 0:
- print("\n[-] Taille 1:")
- elif pos == 2:
- print("\n[-] Taille 2:")
- while True:
- texte = [" [>] Largeur : ", " [>] Hauteur : "]
- dimensions[pos] = input(texte[pos % 2])
- try:
- dimensions[pos] = int(dimensions[pos].strip())
- break
- except:
- print(" >>>ERREUR<<< Valeur incorrecte.")
- configuration["largeur1"] = dimensions[0]
- configuration["hauteur1"] = dimensions[1]
- configuration["largeur2"] = dimensions[2]
- configuration["hauteur2"] = dimensions[3]
- config.sauvegarde(json_path, configuration)
- print("\n[-] Modification effectue.")
+ ui.affichage_banner()
+ configuration["dimensions"] = ui.question_taille(
+ configuration["dimensions"]
+ )
+ config.sauvegarde(configuration)
ui.affichage_fin()
break
elif choix.strip() == "6":
ui.reset_screen()
- nouveau_background_color = [0, 0, 0]
- print("\n[-] Modification de la couleur du background (Valeur RGB 0-255):\n")
- for pos, i in enumerate(configuration["background_color"]):
- while True:
- texte = [" [>] Valeur Rouge: ", " [>] Valeur Vert: ", " [>] Valeur Bleu: "]
- nouveau_background_color[pos] = input(texte[pos])
- try:
- nouveau_background_color[pos] = int(nouveau_background_color[pos].strip())
- if nouveau_background_color[pos] >= 0 and nouveau_background_color[pos] < 256:
- break
- else:
- print(" >>>ERREUR<<< Valeur incorrecte.")
- except:
- print(" >>>ERREUR<<< Valeur incorrecte.")
- configuration["background_color"] = nouveau_background_color
- config.sauvegarde(json_path, configuration)
- print("\n[-] Modification effectue.")
+ ui.affichage_banner()
+ configuration["background"] = ui.question_background(
+ configuration["background"]
+ )
+ config.sauvegarde(configuration)
ui.affichage_fin()
break
elif choix.strip() == "7":
- print("\n[-] Modification du format de sortie:\n")
- nombre = 1
- for i in formats_acceptes:
- nombre_choix = "(" + str(nombre) + ") ->"
- print(" ", nombre_choix, i)
- nombre += 1
- nouveau_format = input("\n[>] Choix (numero) : ")
- try:
- nouveau_format = int(nouveau_format.strip())
- if nouveau_format > 0:
- configuration["format_final"] = "." + formats_acceptes[nouveau_format - 1]
- config.sauvegarde(json_path, configuration)
- print("\n[-] Modification effectue.")
- else:
- print(">>>ERREUR<<< Choix invalide.")
- ui.affichage_fin()
- break
- except:
- print(">>>ERREUR<<< Choix invalide.")
+ ui.reset_screen()
+ ui.affichage_banner()
+ configuration["format_final"] = ui.question_format_final(
+ configuration["formats_acceptes"]
+ )
+ config.sauvegarde(configuration)
ui.affichage_fin()
break
elif choix.strip() == "8":
ui.reset_screen()
+ ui.affichage_banner()
print("\n[-] Reset des parametres.")
- configuration["largeur1"] = 500
- configuration["hauteur1"] = 350
- configuration["largeur2"] = 900
- configuration["hauteur2"] = 900
- configuration["background_color"] = [255, 255, 255]
- configuration["format_final"] = ".webp"
- config.sauvegarde(json_path, configuration)
- print("\n[-] Modification effectue.")
+ config.sauvegarde(config._base_configuration)
ui.affichage_fin()
break
elif choix.strip() == "9":
- if platform != "linux":
- system("cls")
- else:
- system("clear")
+ ui.reset_screen()
exit(0)
else:
+ ui.reset_screen()
+ ui.affichage_banner()
print("\n[-] Reponse invalide .")
ui.affichage_fin()
break
diff --git a/Redim/ui.py b/Redim/ui.py
index 5d21efd..a5c5fc4 100644
--- a/Redim/ui.py
+++ b/Redim/ui.py
@@ -3,32 +3,35 @@ from sys import platform
class Ui:
- def __init__(self, configuration, formats_acceptes):
+ def __init__(self, configuration):
self.banner = (
- "\n ____ _ ____ ____ \n",
- "| _ \\ _ __ ___ _ __ (_)_ _ _ __ ___ | _ \\ / ___|\n",
- "| |_) | '__/ _ \\ '_ \\| | | | | '_ ` _ \\| |_) | | \n",
- "| __/| | | __/ | | | | |_| | | | | | | __/| |___ \n",
- "|_| |_| \\___|_| |_|_|\\__,_|_| |_| |_|_| \\____|\n",
- "\n######################################################\n",
- "\n[-] taille 1:", configuration["largeur1"], "x", configuration["hauteur1"],
- ", taille 2:", configuration["largeur2"], "x", configuration["hauteur2"],
- "\n[-] rgb background:", configuration["background_color"],
- "\n[-] formats acceptes:", formats_acceptes,
- "\n[-] format de sortie:", configuration["format_final"],
- "\n\n######################################################"
- )
+ "\n ____ _ ____ ____ \n",
+ "| _ \\ _ __ ___ _ __ (_)_ _ _ __ ___ | _ \\ / ___|\n",
+ "| |_) | '__/ _ \\ '_ \\| | | | | '_ ` _ \\| |_) | | \n",
+ "| __/| | | __/ | | | | |_| | | | | | | __/| |___ \n",
+ "|_| |_| \\___|_| |_|_|\\__,_|_| |_| |_|_| \\____|\n",
+ "\n######################################################\n",
+ "\n[-] tailles (lxh): {0}".format(
+ ", ".join(map(
+ str,
+ ["x".join(map(str, configuration["dimensions"][i]))
+ for i in range(len(configuration["dimensions"]))]
+ ))
+ ),
+ "\n[-] rgb background:", configuration["background"],
+ "\n[-] formats acceptes:", configuration["formats_acceptes"],
+ "\n[-] format de sortie:", configuration["format_final"],
+ "\n\n######################################################"
+ )
self.menu = (
- "\n[-] Que faire?\n",
- "\n (1) -> Conversion (",
- configuration["largeur1"], "x", configuration["hauteur1"], "px et",
- configuration["largeur2"], "x", configuration["hauteur2"], "px)",
- "\n (5) -> Modification des tailles",
- "\n (6) -> Modification du RGB",
- "\n (7) -> Modification du format de sortie",
- "\n (8) -> Reset des parametres",
- "\n (9) -> Quitter\n"
- )
+ "\n[-] Que faire?\n",
+ "\n (1) -> Conversions",
+ "\n (5) -> Modification des tailles",
+ "\n (6) -> Modification du RGB",
+ "\n (7) -> Modification du format de sortie",
+ "\n (8) -> Reset des parametres",
+ "\n (9) -> Quitter\n"
+ )
def affichage_banner(self):
print(*self.banner)
@@ -36,8 +39,78 @@ class Ui:
def affichage_menu(self):
print(*self.menu)
+ def question_taille(self, configuration):
+ texte = [
+ " [>] Largeur : ",
+ " [>] Hauteur : "
+ ]
+ tailles = []
+ for i in range(len(configuration)):
+ print("\n[-] Taille {0!s}:".format(i + 1))
+ dimensions = []
+ for j in range(len(texte)):
+ while True:
+ reponse = input(texte[j])
+ try:
+ reponse = int(reponse.strip())
+ if reponse > 0:
+ dimensions.append(reponse)
+ break
+ else:
+ print(" >>>ERREUR<<< Valeur incorrecte.")
+ except:
+ print(" >>>ERREUR<<< Valeur incorrecte.")
+ tailles.append(dimensions)
+ return tailles
+
+ def question_background(self, configuration):
+ texte = [
+ " [>] Valeur Rouge: ",
+ " [>] Valeur Vert: ",
+ " [>] Valeur Bleu: "
+ ]
+ background = []
+ print(
+ "\n[-] Modification de la couleur"
+ " du background (Valeur RGB 0-255):\n"
+ )
+ for i in range(len(configuration)):
+ while True:
+ reponse = input(texte[i])
+ try:
+ reponse = int(reponse.strip())
+ if reponse >= 0 and reponse < 256:
+ background.append(reponse)
+ break
+ else:
+ print(" >>>ERREUR<<< Valeur incorrecte.")
+ except:
+ print(" >>>ERREUR<<< Valeur incorrecte.")
+ return background
+
+ def question_format_final(self, configuration):
+ print("\n[-] Modification du format de sortie:\n")
+ for pos, i in enumerate(configuration):
+ print(
+ " ("
+ + str(pos + 1)
+ + ") ->",
+ i
+ )
+ while True:
+ reponse = input("\n[>] Choix (numero) : ")
+ try:
+ reponse = int(reponse.strip())
+ if reponse > 0:
+ format_final = "." + configuration[reponse - 1]
+ return format_final
+ else:
+ print(">>>ERREUR<<< Choix invalide.")
+ except:
+ print(">>>ERREUR<<< Choix invalide.")
+
def affichage_fin(self):
- input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
+ input("\n[-] fin, appuyer sur \'entrer\' pour continuer.")
def reset_screen(self):
if platform != "linux":
diff --git a/Redim.spec b/redim.spec
index 90e7672..90e7672 100644
--- a/Redim.spec
+++ b/redim.spec