Cordialement à tous. Je développe un système de compression d'image en utilisant Python Image Library. Le flux de travail de base est:Comment utiliser Python re module pour remplacer n avec rien dans un seul fichier
- Lire toutes les images d'un répertoire avec: find/opt/images -nom * .jpg> /opt/rs/images.txt
- lire ce fichier et de stockage dans le résultat une liste Python
- Itérer la liste, créez un objet image et en passant comme un argument pour la fonction de compression
- et, copiez l'image résultante sur un répertoire qui est buit en fonction du nom de l'image.
Un exemple: /opt/buzon/17_499999_1_00000000_00000999_1.jpg Ceci est le vrai nom de l'image: Le résultat final est: 17_499999.jpg Le répertoire est ouput:/opt/ftp et devrait être storaged sur cette voie: 1- première partition 00000000 - deuxième partition 00000999 - troisième partition 1- ce drapeau si de décider si nous devons compresser cette image ou non (1 est faux, 0 est vrai)
Pour cette raison, le chemin final de l'image est: /opt/ftp/1/00000000/00000999/17_499999.jpg pour la copie originale /opt/ftp/1/00000000/00000999/17_499999_tumb.jpg
Maintenant, où est le problème. Lorsque je lis le fichier où je stocke le résultat de la commande find, chaque ligne du fichier a le caractère \ n.
Comment puis-je remplacer avec des expressions régulières cela?
Le code source complété est le suivant. Toute suggestion est la bienvenue.
import Image, os ,sys, re, subprocess, shlex
import ConfigParser
from symbol import except_clause
CONFIG_FILE = "/opt/scripts/config.txt"
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
entry_dir = config.get('directories', 'entry_dir')
out_dir = config.get('directories', 'out_dir')
def resize(img, box, fit, out):
'''Downsample the image.
@param img: Un objeto de la clase Imagen
@param box: tuple(x, y) - El recuadro de la imagen resultante
@param fix: boolean - el corte de la imagen para llenar el rectangulo
@param out: objeto de tipo fichero - guarda la imagen hacia la salida estandar
'''
# prepara la imagen con un factor de 2, 4, 8 y el algoritmo mas rapido
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
# Aqui se calcula el rectangulo optimo para la imagen
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = y2/2-box[1]*wRatio/2
y2 = y2/2+box[1]*wRatio/2
else:
x1 = x2/2-box[0]*hRatio/2
x2 = x2/2+box[0]*hRatio/2
# Este metodo es para manipular rectangulos de una determinada imagen
# definido por 4 valores que representan las coordenadas: izquierda,
# arriba, derecha y abajo
img = img.crop((x1,y1,x2,y2))
# Le damos el nuevo tamanno a la imagen con el algoritmo de mejor calidad(ANTI-ALIAS)
img.thumbnail(box, Image.ANTIALIAS)
return img
def removeFiles(directory):
"""
Funcion para borrar las imagenes luego de ser procesadas
"""
for f in os.listdir(directory):
path = os.path.abspath(f)
if re.match("*.jpg", path):
try:
print "Erasing %s ..." % (path)
os.remove(path)
except os.error:
pass
def case_partition(img):
"""
@desc: Esta funcion es la que realmente guarda la imagen en la
particion 0
@param: imagen a guardar
@output_dir: Directorio a guardar las imagenes
"""
nombre_imagen = img
nombre_import = os.path.splitext(nombre_imagen)
temp = nombre_import[0]
nombre_real = temp.split('_')
if nombre_real[4] == 0:
ouput_file = nombre_real[0] + nombre_real[1] + ".jpg"
output_dir = out_dir + "/%d/%d/%d/" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file)
else:
print "Esta imagen sera comprimida"
img = resize(img, 200, 200, 200) ## FIXME Definir el tamano de la imagen
# Salvamos la imagen hacia un objeto de tipo file
# con la calidad en 75% en JPEG y el nombre definido por los especialistas
# Este nombre no esta definido......
# FIXME
output_file = nombre_real[0] + nombre_path[1] + "_.jpg"
output_dir = out_dir + "/%d/%d" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(out)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
if __name__ == "__main__":
find = "find %s -name *.jpg > /opt/scripts/images.txt" % entry_dir
args = shlex.split(find)
p = subprocess.Popen(args)
f = open('/opt/scripts/images.txt', "r")
images = []
for line in f:
images.append(line)
f.close()
for i in images:
img = Image.open(filename) # Here is the error when I try to open a file
case_partition(img) # with the format '/opt/buzon/15_498_3_00000000_00000000_1.jpg\n'
# and the \n character is which I want to replace with nothing
removeFiles(entry_dir) #
#
salutations