Tratamiento básico de Imágenes con Python para usar en desarrollo Web
February 28th, 2008 by BusindreGallery.py es un simple script desarrollado en Python para ser usado en la creación o tratamiento de galerías de imágenes destinadas a Web. El script puede mostrar el tamaño (Resolución) de una imagen, cambiar el tamaño de las imágenes, generar miniaturas (thumbs) e incluso mostrar una salida en código Html con las miniaturas y las imágenes pertenecientes a esa miniaturas. Es muy útil para facilitarnos ciertas tareas o para usar desde la propia aplicación web que estemos desarrollando, para ver la funcionalidad del script veamos unos ejemplos de uso, uno por cada opción disponible.
Dependencia: http://www.pythonware.com/products/pil/
Instalar / Compilar Pil (Python Imaging Library)
$ wget http://effbot.org/downloads/Imaging-1.1.6.tar.gz
$ tar -zxvf Imaging-1.1.6.tar.gz
$ cd Imaging-1.1.6
$ python setup.py build
# python setup.py install
Crear codigo Html:
$ python gallery.py --html /home/busi/Imagenes/Peace-1600x1200.jpg
NOTA: Podemos usarlo con ">" : python gallery.py --html /home/busi/Imagenes/Peace1.png > Peace.html
Mostrar resolución de imagen:
$ python gallery.py --size /home/busi/Imagenes/Peace-1600x1200.jpg
/home/busi/Imagenes/Peace-1600x1200.jpg : 1600 1200
Cambiar resolución de imagen:
$ python gallery.py --resize 800 600 /home/busi/Imagenes/Peace-1600x1200.jpg
/home/busi/Imagenes/Peace-1600x1200.jpg: was 1600,1200; resizing to 800,600
$ python gallery.py --size /home/busi/Imagenes/Peace-1600x1200.jpg
/home/busi/Imagenes/Peace-1600x1200.jpg : 800 600
Crear ficheros thumb (Miniaturas) de las imagenes:
$ python Descargas/gallery.py --thumbnail 100 100 /home/busi/Imagenes/planetarium.jpg
/home/busi/Imagenes/planetarium.jpg
$ ls /home/busi/Imagenes/planetarium*
/home/busi/Imagenes/planetarium.jpg /home/busi/Imagenes/planetarium_thumb.jpg
Error:
$ python gallery.py --html /home/busi/Imagenes/planetarium.jpg
gallery.py: thumbnail /home/busi/Imagenes/planetarium_thumb.jpg doesn't exist
....
IOError: [Errno 2] No such file or directory: '/home/busi/Imagenes/planetarium_thumb.jpg'
NOTA: Para poder hacer uso de la opción --html necesitamos tener creado el fichero "thumb" de la imagen, ya que sera la usada para mostrar en la pagina html, la cual enlaza a la original. Cualquier fichero con la sintaxis *_thumb.* será considerado como un fichero thumb.
import sys, os, getopt
try:
from PIL import Image
except ImportError:
print>>sys.stderr, ("Unable to import PIL.Image; "
"is the Python Imaging Library installed?")
sys.exit(0)
__version__ = '1.01'
__doc__ = """%s [option] file1 file2
Options:
--help Display this usage message
--html Output HTML to stdout
--resize x y Resize specified images to x,y
--size Display the image sizes
--thumbnail x y Make thumbnails of specified images, ignoring existing
thumbnails that happen to be listed among the files.
If a filename is of the form *_thumb.*, it's assumed to be a thumbnail.
""" % sys.argv[0]
def is_thumbnail (filename):
"Returns true if the filename is for a thumbnail"
root, ext = os.path.splitext(filename)
return root.endswith('_thumb')
def thumbnail_name (filename):
"""Return the thumbnail form of a filename,
converting foo.jpg to foo_thumb.jpg.
"""
assert not is_thumbnail(filename)
root, ext = os.path.splitext(filename)
return root + '_thumb' + ext
def output_html (args):
for filename in args:
if is_thumbnail(filename): continue
thumbnail = thumbnail_name(filename)
if not os.path.exists(thumbnail):
print>>sys.stderr, ("%s: thumbnail %s doesn't exist" %
(sys.argv[0], thumbnail) )
im = Image.open(thumbnail)
width, height = im.size
print ('<p><a href="%s"><img src="%s" width="%i" height="%i" '
'alt="XXX" align="XXX"></a>'
'\n\nXXX\n'
'<br clear=all><hr>\n\n'
% (filename, thumbnail, width, height) )
def make_thumbnails (args):
x, y = int(args[0]), int(args[1])
args = args[2:] ; args.sort()
for filename in args:
if is_thumbnail(filename): continue
thumbnail = thumbnail_name(filename)
print>>sys.stderr, filename
im = Image.open(filename)
im.thumbnail((x,y))
im.save(thumbnail)
def resize_images (args):
x, y = int(args[0]), int(args[1])
args = args[2:] ; args.sort()
for filename in args:
im = Image.open(filename)
w,h = im.size
im2 = im.resize((x,y))
print>>sys.stderr, ('%s: was %i,%i; resizing to %i,%i'
% (filename, w,h, x,y) )
im2.save(filename)
def main ():
opts, args = getopt.getopt(sys.argv[1:],
'h',
['help',
'html',
'resize',
'size',
'thumbnail'])
# Remove the unused option arguments
opts = [opt for opt,arg in opts]
# Print usage message if requested
if '-h' in opts or '--help' in opts:
print>>sys.stderr, __doc__
sys.exit(0)
# Ensure that exactly one option is supplied
if len(opts) == 0:
print>> sys.stderr, ("%s: must specify one of --size, --help"
"\n --html, --resize, --thumbnail" %
sys.argv[0] )
sys.exit(0)
elif len(opts)> 1:
print>> sys.stderr, ("%s: cannot specify multiple options" %
sys.argv[0] )
sys.exit(0)
# Perform each of the possible actions
opt = opts[0]
if opt == '--html':
output_html(args)
elif opt == '--resize':
resize_images(args)
elif opt == '--size':
for filename in args:
image = Image.open(filename)
x, y = image.size
print filename, ':', x,y
elif opt == '--thumbnail':
make_thumbnails(args)
else:
print>>sys.stderr, ("%s: unknown option" % sys.argv[0])
if __name__ == '__main__':
main()
Posted in How To |
February 28th, 2008 at 11:01 am
Muy buena la utilidad, aunque yo prefiero utilizar GIMP para estos temas, porque creo que en la práctica es más rápido.
February 28th, 2008 at 5:53 pm
Sí, es cuestión de gustos, pero cuando tienes que redimensionar 700 imágenes,.. ya es mucha tela estar usando gimp para cada una de ellas.
Otro problema es usar Gimp por linea de comando para usar sus múltiples facultades en nuestra Web para el tratamiento de imágenes en galerías, que es un poco para lo que está orientado.
Saludos!