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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
|
#!/usr/bin/python
"""
Nécessite Pillow & PyQt5
"""
import json
from os import system, listdir, mkdir, environ, getenv
from os.path import join, isfile, isdir, getmtime
from sys import platform, exit
from time import time
from shutil import rmtree
from PIL.Image import ANTIALIAS
from PIL.Image import new as image_new
from PIL.Image import open as image_open
from PyQt5.QtWidgets import QFileDialog, QApplication, QWidget
class Redim():
def __init__(self, formats_acceptes):
self.formats_acceptes = formats_acceptes
def start(self, dossier, larg, haut, background_color, format_final):
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)
def nettoyage_pyinstaller(self):
for i in listdir(environ["TMP"]):
if i.startswith("_MEI") and isdir(i) and (int(getmtime(join(environ["TMP"], i))) < (time() - 86400)):
rmtree(join(environ["TMP"], i))
def reset_screen(banner):
if platform != "linux":
system("cls")
else:
system("clear")
print(*banner)
def sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final):
dictionnaire = {
"dimensions" : [[largeur1, hauteur1], [largeur2,hauteur2]],
"background_color" : background_color,
"format_final" : format_final
}
if not isdir(json_path):
mkdir(json_path)
with open(join(json_path, "config_redim"), "w") as f:
json.dump(dictionnaire, f)
def lecture_json(json_path):
with open(join(json_path, "config_redim"), "r") as f:
dictionnaire = json.load(f)
largeur1 = dictionnaire["dimensions"][0][0]
hauteur1 = dictionnaire["dimensions"][0][1]
largeur2 = dictionnaire["dimensions"][1][0]
hauteur2 = dictionnaire["dimensions"][1][1]
background_color = dictionnaire["background_color"]
format_final = dictionnaire["format_final"]
return largeur1, hauteur1, largeur2, hauteur2, background_color, format_final
if __name__ == "__main__":
largeur1 = 500
hauteur1 = 350
largeur2 = 900
hauteur2 = 900
background_color = [255, 255, 255]
format_final = ".webp"
formats_acceptes = ("jpg", "jpeg", "png", "bmp", "gif", "webp")
json_path = join(getenv("USERPROFILE"), "AppData", "Local", "Redim")
app = QApplication([])
widget = QWidget()
while True:
redim = Redim(formats_acceptes)
if not isfile(join(json_path, "config_redim")):
sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final)
else:
largeur1, hauteur1, largeur2, hauteur2, background_color, format_final = lecture_json(json_path)
if platform != "linux":
redim.nettoyage_pyinstaller()
banner = (
"\n ____ _ ____ ____ \n",
"| _ \\ _ __ ___ _ __ (_)_ _ _ __ ___ | _ \\ / ___|\n",
"| |_) | '__/ _ \\ '_ \\| | | | | '_ ` _ \\| |_) | | \n",
"| __/| | | __/ | | | | |_| | | | | | | __/| |___ \n",
"|_| |_| \\___|_| |_|_|\\__,_|_| |_| |_|_| \\____|\n",
"\n######################################################\n",
"\n[-] taille 1:", largeur1, "x", hauteur1, ", taille 2:", largeur2, "x", hauteur2,
"\n[-] rgb background:", background_color,
"\n[-] formats acceptes:", formats_acceptes,
"\n[-] format de sortie:", format_final,
"\n\n######################################################"
)
menu = (
"\n[-] Que faire?\n",
"\n (1) -> Conversion (", largeur1, "x", hauteur1, "px et", largeur2, "x", 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"
)
reset_screen(banner)
print(*menu)
choix = input("[>] Choix (numero) : ")
while True:
reset_screen(banner)
if choix.strip() == "1":
dossier = QFileDialog.getExistingDirectory(
widget,
"Dossier a travailler."
)
print("\n[-] travail pour", largeur1, "x", hauteur1, "px :")
redim.start(dossier, largeur1, hauteur1, tuple(background_color), format_final)
print("\n[-] travail pour", largeur2, "x", hauteur2, "px :")
redim.start(dossier, largeur2, hauteur2, tuple(background_color), format_final)
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
elif choix.strip() == "5":
reset_screen(banner)
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.")
largeur1 = dimensions[0]
hauteur1 = dimensions[1]
largeur2 = dimensions[2]
hauteur2 = dimensions[3]
sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final)
print("\n[-] Modification effectue.")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
elif choix.strip() == "6":
reset_screen(banner)
nouveau_background_color = [0, 0, 0]
print("\n[-] Modification de la couleur du background (Valeur RGB 0-255):\n")
for pos, i in enumerate(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.")
background_color = nouveau_background_color
sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final)
print("\n[-] Modification effectue.")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
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:
format_final = "." + formats_acceptes[nouveau_format - 1]
sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final)
print("\n[-] Modification effectue.")
else:
print(">>>ERREUR<<< Choix invalide.")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
except:
print(">>>ERREUR<<< Choix invalide.")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
elif choix.strip() == "8":
reset_screen(banner)
print("\n[-] Reset des parametres.")
largeur1 = 500
hauteur1 = 350
largeur2 = 900
hauteur2 = 900
background_color = [255, 255, 255]
format_final = ".webp"
sauvegarde_json(json_path, largeur1, hauteur1, largeur2, hauteur2, background_color, format_final)
print("\n[-] Modification effectue.")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
elif choix.strip() == "9":
if platform != "linux":
system("cls")
else:
system("clear")
exit(0)
else:
print("\n[-] Reponse invalide .")
input("\n[-] fin, appuyer sur \'entrer\' pour recommencer .")
break
|