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.
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import Image
- class Imagen(object):
- def __init__(self):
- return
-
- def proporcion(size, ancho=0, alto=0):
- h, w = size[0], size[1]
- if ancho:
- x100to = (100.0 / h) * ancho
- if alto:
- x100to = (100.0 / w) * alto
- h1 = (h / 100.0) * x100to
- w1 = (w / 100.0) * x100to
- return (int(h1), int(w1))
-
- def ImgResize(self, img, ancho, alto=None):
- """img es una instancia del modulo Image. Si no se especifica un
- alto, se cambia el tamano proporcionalmente al ancho especificado.
- imageobj -> imageobje
- """
- size = (ancho, alto)
- if not alto:
- size = img.size
- prop = float(size[0]) / ancho
- alto = float(size[1]) / prop
- size = (int(ancho), int(alto))
- return img.resize(size, Image.ANTIALIAS)
-
- def ImgGetThumbnail(img, size, resample=0):
- """Crea un thumbnail de la imagen indicada.
- """
- return img.thumbnail(size, resample)
-
- def ImgResizeProportion(self, img, intproportion):
- """resize el imagen objeto de acuerdo a la proporcion indicada
- Imageobj -> Imageobje
- """
- ancho, alto = img.size
- ancho = int((ancho / 100) * intproportion)
- alto = int((alto / 100) * intproportion)
- return self.ImgResize(img, ancho, alto)
-
- def ImgResizeProportionFromPath(self, path, intproportion):
- """Ver ImgResizeProportion.
- """
- img = self.ImgOpen(path)
- return self.ImgResizeProportion(img, intproportion)
-
- def ImgResizeFromPath(self, path, ancho, alto=None):
- """Imageobj -> Imageobj, ver ImgResize
- """
- img = self.ImgOpen(path)
- return self.ImgResize(img, ancho, alto)
-
- def ImgOpen(self, path):
- """strpath -> Imageobj.
- """
- return Image.open(path)
-
- def ImgSave(self, img, outpath):
- """Crea una imagen fisica en el outpath, a partir del Image obj.
- """
- return img.save(outpath)
-
- def ImgNew(self, size, color=0):
- """Crea un nuevo objeto Image.
- """
- return Image.new(size, color)