Código de Python - Unificador para fotos de vacaciones

Imágen de perfil

Unificador para fotos de vacacionesgráfica de visualizaciones


Python

Publicado el 19 de Agosto del 2015 por Neogurb
3.867 visualizaciones desde el 19 de Agosto del 2015
Este verano he sufrido una triste experiencia: salir de vacaciones con mi señora e hijos, todos nosotros equipados con nuestra cámara y/o teléfono. Lo triste no es esto en sí, sino llegar a casa e intentar organizar las fotos que hemos tomado cada uno de nosotros para hacer un álbum común. Cada cacharro utiliza una nomenclatura distinta, por lo que al mezclar las fotos en una carpeta, se arma un sindiós y las vemos en un orden que nadie entiende.

Este programita intenta solucionar ese problema, basándose en los datos EXIF de las fotografías (concretamente, fecha y hora).

Es muy sencillo: coge todos esos cacharros, copia todas las fotos en una carpeta, y organízala con el programa que te mando. Quedarán ordenadas por fecha y hora, con independencia de quién hizo la foto con qué aparato.

organizar-fotos-python

Requerimientos

Pyhton 2.7

1.0
estrellaestrellaestrellaestrellaestrella(3)

Publicado el 19 de Agosto del 2015gráfica de visualizaciones de la versión: 1.0
3.868 visualizaciones desde el 19 de Agosto del 2015
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
# -*- coding: utf-8 -*-
 
 
import wx
import os
import datetime
import time
import random
import string
from PIL import Image
from PIL.ExifTags import TAGS
 
 
 
class MyForm(wx.Frame):
 
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,
            u'Organizador de fotografías',
            size=(450,400))
        panel = wx.Panel(self, wx.ID_ANY)
 
        self.btAbre = wx.Button(panel, label="1.- Selecciona directorio con fotos a organizar")
        self.btAbre.Bind(wx.EVT_BUTTON, self.directorio)
        self.lblPrefijo = wx.StaticText(panel, wx.ID_ANY, u'2.- Introduce un prefijo (opcional)')
        self.txtPrefijo = wx.TextCtrl(panel, size=(200, -1))
        self.txtRuta = wx.TextCtrl(panel, size=(400,27))
        self.txtRuta.SetForegroundColour('darkblue')
        self.btOrganiza = wx.Button(panel, label=u'3.- ¡Organiza fotos!')
        self.btOrganiza.Bind(wx.EVT_BUTTON, organiza)
        self.ctInfo = wx.TextCtrl(panel, size=(400,170), style= wx.TE_MULTILINE)
 
        self.txtRuta.SetEditable(False)
        self.ctInfo.SetEditable(False)
        self.btOrganiza.Disable()
 
        self.btAyuda = wx.Button(panel, label='?')
        self.btAyuda.Bind(wx.EVT_BUTTON, self.ayuda)
        self.separador = wx.StaticText(panel, label=' ')
        self.btSalir = wx.Button(panel, label='Salir')
        self.btSalir.Bind(wx.EVT_BUTTON, self.salir)
 
        sizerPrefijo = wx.BoxSizer(wx.HORIZONTAL)
        sizerPrefijo.Add(self.lblPrefijo, 0, wx.ALL|wx.LEFT, 5)
        sizerPrefijo.Add(self.txtPrefijo, 1, wx.EXPAND|wx.ALL|wx.LEFT, 5)
 
        sizerInferior = wx.BoxSizer(wx.HORIZONTAL)
        sizerInferior.Add(self.btAyuda, 0, wx.ALL|wx.LEFT, 5)
        sizerInferior.Add(self.separador, 1, wx.EXPAND|wx.ALL|wx.LEFT, 5)
        sizerInferior.Add(self.btSalir, 1, wx.ALL|wx.RIGHT, 5)
 
 
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.btAbre, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(self.txtRuta, 0, wx.ALL|wx.CENTER, 10)
        sizer.Add(sizerPrefijo, 0, wx.EXPAND|wx.ALL|wx.CENTER, 5)
        sizer.Add(self.btOrganiza, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(self.ctInfo, 1, wx.ALL|wx.CENTER, 10)
        sizer.Add(sizerInferior, 0, wx.EXPAND|wx.ALL|wx.CENTER, 5)
 
        panel.SetSizer(sizer)
 
        self.Centre()
 
    def directorio(self, event):
        carpeta = None
        self.txtRuta.Clear()
        self.ctInfo.Clear()
        dlg = wx.DirDialog(self, u'Escoge un directorio:',
        style=wx.DD_DEFAULT_STYLE
        | wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            carpeta = dlg.GetPath()
            # self.ct.WriteText("Directorio seleccionado: %s" % carpeta)
            self.txtRuta.WriteText(carpeta)
            self.btOrganiza.Enable()
        else:
            self.txtRuta.WriteText(u'Operación Cancelada')
            dlg.Destroy()
        return carpeta
 
 
    def ayuda(self, event):
        texto = 'FotoClas\n\n'
        texto += u'¿Has vuelto de tus vacaciones con un montón de fotos de distintas cámaras y teléfonos, cada uno con su propia nomenclatura? Menudo follón para organizarlas...\n\n'
        texto += u'Esta es una pequeña aplicación que renombra las fotografías de una determinada carpeta, usando su fecha de creación, en formato (Prefijo)-YYYYMMDDHHMMSS\n\n'
        texto += u'Para ello, intenta usar los datos EXIF de la fotografía. En este caso, la fecha será la de la cámara que la tomó.\n\n'
        texto += u'Si esos datos no están disponibles, se usa la fecha del fichero en el disco.\n\n'
        texto += u'Además, se añaden dos letras aleatorias al final, para evitar colisiones de nombres.'
        wx.MessageBox(texto, 'Ayuda')
 
    def salir(self, event):
        self.Destroy()
 
 
 
# http://stackoverflow.com/questions/765396/exif-manipulation-library-for-python
def get_exif(fn):
    ret = {}
    i = Image.open(fn)
    info = i._getexif()
    if info is not None:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if tag=='DateTime':
                print tag
            ret[decoded] = value
    print ret
    return ret
 
 
 
def organiza(self):
 
 
    ruta = frame.txtRuta.GetValue() + os.sep
    if len(frame.txtPrefijo.GetValue()):
        prefijo = frame.txtPrefijo.GetValue() + '-'
    else:
        prefijo = ''
    print prefijo, ruta
 
 
    ficheros = os.listdir(ruta)
    for fichero in ficheros:
        if os.path.isfile(ruta+fichero):
            if fichero.lower()[-4:]=='.jpg':
                nombreOld = ruta + fichero
                rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(2))
                try:
                    fecha = get_exif(nombreOld)['DateTimeOriginal'].replace(':', '').replace(' ','')
                except KeyError:
                    fecha = time.strftime('%Y%m%d%H%M%S', time.localtime(os.path.getmtime(nombreOld)))
                nombreNuevo = ruta + prefijo + fecha + rnd + '.jpg'
                linea = nombreOld.replace(ruta, '') + ' -> ' + nombreNuevo.replace(ruta, '')
                frame.ctInfo.WriteText(linea + '\n')
                os.rename(nombreOld, nombreNuevo)
 
    frame.btOrganiza.Disable()
 
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()



Comentarios sobre la versión: 1.0 (3)

Imágen de perfil
23 de Agosto del 2015
estrellaestrellaestrellaestrellaestrella
Impresionante... muy útil!!!
Responder
caro
13 de Mayo del 2016
estrellaestrellaestrellaestrellaestrella
tengo un problema cuando pongo import wx idle dice que no existe. Primero debo descargarlo?
Responder
Imágen de perfil
14 de Mayo del 2016
estrellaestrellaestrellaestrellaestrella
Sí, es la librería wxPython, que permite su visualización.
http://www.wxpython.org/
Responder

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s3256