Manejo de imágenes en Python

Aquí una implementación del modulo Python "Image" de la librería "PIL", para el manejo de imágenes.





  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-


  3. import Image


  4. class Imagen(object):

  5.     def __init__(self):
  6.         return
  7.         
  8.     def proporcion(size, ancho=0, alto=0):
  9.         h, w = size[0], size[1]
  10.         if ancho:
  11.             x100to = (100.0 / h) * ancho
  12.         if alto:
  13.             x100to = (100.0 / w) * alto
  14.         h1 = (h / 100.0) * x100to
  15.         w1 = (w / 100.0) * x100to
  16.         return (int(h1), int(w1))
  17.   

  18.     def ImgResize(self, img, ancho, alto=None):
  19.         """img es una instancia del modulo Image. Si no se especifica un
  20.         alto, se cambia el tamano proporcionalmente al ancho especificado.
  21.         imageobj -> imageobje
  22.         """
  23.         size = (ancho, alto)
  24.         if not alto:
  25.             size = img.size
  26.             prop = float(size[0]) / ancho
  27.             alto = float(size[1]) /  prop
  28.             size = (int(ancho), int(alto))
  29.         return img.resize(size, Image.ANTIALIAS)

  30.     
  31.     def ImgGetThumbnail(img, size, resample=0):
  32.         """Crea un thumbnail de la imagen indicada.
  33.         """
  34.         return img.thumbnail(size, resample)

  35.     
  36.     def ImgResizeProportion(self, img, intproportion):
  37.         """resize el imagen objeto de acuerdo a la proporcion indicada
  38.         Imageobj -> Imageobje
  39.         """
  40.         ancho, alto = img.size
  41.         ancho = int((ancho / 100) * intproportion)
  42.         alto = int((alto / 100) * intproportion)
  43.         return self.ImgResize(img, ancho, alto)
  44.     

  45.     def ImgResizeProportionFromPath(self, path, intproportion):
  46.         """Ver ImgResizeProportion.
  47.         """
  48.         img = self.ImgOpen(path)
  49.         return self.ImgResizeProportion(img, intproportion)

  50.     
  51.     def ImgResizeFromPath(self, path, ancho, alto=None):
  52.         """Imageobj -> Imageobj, ver ImgResize
  53.         """
  54.         img = self.ImgOpen(path)
  55.         return self.ImgResize(img, ancho, alto)

  56.     
  57.     def ImgOpen(self, path):
  58.         """strpath -> Imageobj.
  59.         """
  60.         return Image.open(path)

  61.     
  62.     def ImgSave(self, img, outpath):
  63.         """Crea una imagen fisica en el outpath, a partir del Image obj.
  64.         """
  65.         return img.save(outpath)

  66.     
  67.     def ImgNew(self, size, color=0):
  68.         """Crea un nuevo objeto Image.
  69.         """
  70.         return Image.new(size, color)