Visualizzazione post con etichetta pil. Mostra tutti i post
Visualizzazione post con etichetta pil. Mostra tutti i post

mercoledì 8 luglio 2009

Some code for writing some metadata within a png with PIL

Some functions I've written adapting some code of Nick Galbreath from http://mail.python.org/pipermail/image-sig/2007-August/004575.html .

#convert an image to png format
def convert_to_png(imagename, destPath):

filename = os.path.abspath(destPath)+'\\'+(os.path.basename(imagename)[0:-4])+".png"

if(os.path.basename(imagename)[-3:]!="png"):

cmmd = "convert "+imagename+" "+filename
os.system(cmmd)

return filename


#save the metadata dictionary to be loaded within the sourceimage into a new name file
def pngsave(sourceImage, metadataDict, filename):

from PIL import PngImagePlugin
#reserved = sourceImage.info

meta = PngImagePlugin.PngInfo()


# copy from Image.info to new dict
for k,v in metadataDict.iteritems():

#if k in reserved: continue
meta.add_text(k, str(v), 0)

# and save
sourceImage.save(filename, "PNG", pnginfo=meta)

I should write some fixing for jpg metadata.

mercoledì 13 maggio 2009

giovedì 23 aprile 2009

Image to Array, array to Image

http://mail.python.org/pipermail/python-list/2000-August/046892.html

These are code and comments from the code above:


It is straightforward to convert Numeric arrays into PIL images:
#--------------------
from Numeric import *
from Pil import Image

# construct an arbitrary Numeric matrix
dims = (256,256)
arr = zeros(dims,Int8)
for i in xrange(dims[0]):
arr[i,i] = 255

# and convert it to an Image
img = Image.fromstring('L',dims,arr.tostring())
img.save('foo.gif')
#--------------------

or to convert from a PIL image back to a Numeric array:

#--------------------
from Numeric import *
from Pil import Image

newImg = Image.open('foo.gif')
newArr = fromstring(newImg.tostring(),Int8)
newArr = reshape(newArr,newImg.size)
#-------------------

If you are constructing images from Numeric arrays, don't forget that
the Image values should run from 0-255, so you'll need to scale your
data in the Numeric array before creating the image.