Redimensionner toutes les images d'un dossier

Contenu du snippet

Cette source est mon premier programme en Python.
J'ai utilisé wxPython et Boa Constructor pour le GUI, PIL pour le traitement d'image.
J'ai crée ce petit programme par nécessité de redimensionner rapidement toutes les images d'un dossier, principalement les photos en provenance de mon appareil photo numérique.

Pour faire tourner ce script, il vous faudra installer xwPython et PIL, si ce n'est pas déja fait.
J'espere que cette source sera utile :)

Source / Exemple :


#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

#pyThumbs - Auteur: JBJ

import wx, os, sys, glob, string, Image
import JpegImagePlugin

#import Frame1

#modules ={'Frame1': [1, 'Main frame of Application', u'Frame1.py']}

def create(parent):
    return Frame1(parent)

def resizeImage(image, hauteur, largeur, destination):
	try:
		img = Image.open(image).convert("RGB")
		img.thumbnail((hauteur,largeur), Image.ANTIALIAS)
		img.save(destination)
		return True

	except Error:
		return False
		
def resizeFolder(folder, hauteur, largeur):
	try:
		os.chdir(folder)
		os.mkdir("thumbs")
		compteur_img = 0
		for nom in glob.glob('*.jpg'):
			compteur_img+=1
			nomImage = os.path.join(folder,"thumbs", "Image"+`compteur_img`+".jpg")
			resizeImage(nom, hauteur, largeur, nomImage)
		
		return True

	except OSError:
		return False

[wxID_FRAME1, wxID_FRAME1CHEMIN, wxID_FRAME1HAUTEUR, wxID_FRAME1LONGUEUR, 
 wxID_FRAME1PANEL1, wxID_FRAME1PARCOURIR, wxID_FRAME1REDIMENSIONNER, 
 wxID_FRAME1STATICLINE1, wxID_FRAME1STATICLINE2, wxID_FRAME1STATICLINE3, 
 wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2, wxID_FRAME1STATICTEXT3, 
 wxID_FRAME1STATUS, wxID_FRAME1STATUSBAR1, 
] = [wx.NewId() for _init_ctrls in range(15)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(301, 152), size=wx.Size(400, 300),
              style=wx.DEFAULT_FRAME_STYLE, title=u'JBJ pyThumbs')
        self.SetClientSize(wx.Size(392, 266))

        self.statusBar1 = wx.StatusBar(id=wxID_FRAME1STATUSBAR1,
              name='statusBar1', parent=self, style=0)
        self.statusBar1.SetLabel(u'JBJ pyThumbs - 2006 Jean-Baptiste Jung')
        self.SetStatusBar(self.statusBar1)

        self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(392, 243),
              style=wx.TAB_TRAVERSAL)

        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label=u'Dossier \xe0 redimensionner :', name='staticText1',
              parent=self.panel1, pos=wx.Point(8, 16), size=wx.Size(127, 13),
              style=0)

        self.chemin = wx.TextCtrl(id=wxID_FRAME1CHEMIN, name=u'chemin',
              parent=self.panel1, pos=wx.Point(8, 40), size=wx.Size(256, 21),
              style=0, value=u'')

        self.parcourir = wx.Button(id=wxID_FRAME1PARCOURIR,
              label=u'Parcourir...', name=u'parcourir', parent=self.panel1,
              pos=wx.Point(288, 40), size=wx.Size(96, 23), style=0)
        self.parcourir.Bind(wx.EVT_BUTTON, self.OnParcourirButton,
              id=wxID_FRAME1PARCOURIR)

        self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
              label=u'Longueur :', name='staticText2', parent=self.panel1,
              pos=wx.Point(8, 92), size=wx.Size(52, 21), style=0)

        self.longueur = wx.TextCtrl(id=wxID_FRAME1LONGUEUR, name=u'longueur',
              parent=self.panel1, pos=wx.Point(72, 88), size=wx.Size(48, 21),
              style=0, value=u'800')
        self.longueur.SetMaxLength(4)

        self.staticLine1 = wx.StaticLine(id=wxID_FRAME1STATICLINE1,
              name='staticLine1', parent=self.panel1, pos=wx.Point(8, 72),
              size=wx.Size(376, 2), style=0)

        self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,
              label=u'Hauteur : ', name='staticText3', parent=self.panel1,
              pos=wx.Point(208, 92), size=wx.Size(49, 13), style=0)

        self.hauteur = wx.TextCtrl(id=wxID_FRAME1HAUTEUR, name=u'hauteur',
              parent=self.panel1, pos=wx.Point(272, 88), size=wx.Size(48, 21),
              style=0, value=u'600')
        self.hauteur.SetMaxLength(4)

        self.redimensionner = wx.Button(id=wxID_FRAME1REDIMENSIONNER,
              label=u'Redimensionner le dossier', name=u'redimensionner',
              parent=self.panel1, pos=wx.Point(8, 160), size=wx.Size(136, 23),
              style=0)
        self.redimensionner.Bind(wx.EVT_BUTTON, self.OnRedimensionnerButton,
              id=wxID_FRAME1REDIMENSIONNER)

        self.staticLine2 = wx.StaticLine(id=wxID_FRAME1STATICLINE2,
              name='staticLine2', parent=self.panel1, pos=wx.Point(184, 128),
              size=wx.Size(1, 2), style=0)

        self.staticLine3 = wx.StaticLine(id=wxID_FRAME1STATICLINE3,
              name='staticLine3', parent=self.panel1, pos=wx.Point(8, 144),
              size=wx.Size(376, 2), style=0)

        self.status = wx.StaticText(id=wxID_FRAME1STATUS, label=u'',
              name=u'status', parent=self.panel1, pos=wx.Point(32, 208),
              size=wx.Size(0, 13), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)

    def OnParcourirButton(self, event):
        dialog = wx.DirDialog( None, message ='Sélectionnez le dossier à redimensionner:' )
	# Show the dialog and get user input
	
	if dialog.ShowModal() == wx.ID_OK:
		self.chemin.SetValue(dialog.GetPath())

	dialog.Destroy()

    def OnRedimensionnerButton(self, event):
        #Récupérer les parametres et utiliser la methode resizeFolder
	erreur = False
	if os.path.isdir(self.chemin.GetValue()):
		folder = self.chemin.GetValue()
	else:
		erreur = True
		self.status.SetLabel(str(self.chemin.GetValue())+" n'est pas un dossier")

	if self.hauteur.GetValue().isdigit() and int(self.hauteur.GetValue()) >0 \
	and int(self.hauteur.GetValue()) <= 2000:
		hauteurimg = int(self.hauteur.GetValue())
			
	else:
		erreur = True
		self.status.SetLabel("la hauteur n'est pas correcte.")

	if self.longueur.GetValue().isdigit() and int(self.longueur.GetValue()) >0 \
	and int(self.longueur.GetValue()) <= 2000:
		largeurimg = int(self.longueur.GetValue())
	
	else:
		erreur = True
		self.status.SetLabel("La longueur n'est pas correcte.")

	if erreur == False:
		self.status.SetLabel("Redimensionnement en cours...")
		if resizeFolder(folder, hauteurimg, largeurimg):
			self.status.SetLabel("Le dossier "+ str(folder)+" à été redimensionné.")

		else:
			self.status.SetLabel("Problème. Vérifiez qu'un dossier du même nom n'existe pas déja.")
	#else:
	#	self.status.SetLabel("Erreur. Vérifiez vos paramètres de redimensionnement.")

class pyThumbs(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        self.main = create(None)
        self.main.Show()
        self.SetTopWindow(self.main)
        return True

def main():
    application = pyThumbs(0)
    application.MainLoop()

if __name__ == '__main__':
    main()

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.

Du même auteur (jbjweb)