Python Imaging Library (PIL) [613950]
Python Imaging Library (PIL)
John W.Shipman
2013-02-20 14:48
Abstract
Describes animage-processing library forthePython programming language.
This publication isavailable inWeb form1andalsoasaPDF document2.Please forward any
comments [anonimizat] .
Table ofCont ents
1.Introduction …………………………………………………………………………………………………………….1
2.Definitions ………………………………………………………………………………………………………………2
2.1.Band ……………………………………………………………………………………………………………..2
2.2.Modes …………………………………………………………………………………………………………..2
2.3.Sizes ……………………………………………………………………………………………………………..2
2.4.Coordinates ……………………………………………………………………………………………………2
2.5.Angles …………………………………………………………………………………………………………..2
2.6.Bboxes (bounding boxes) …………………………………………………………………………………..3
2.7.Colors ……………………………………………………………………………………………………………3
2.8.Filters ……………………………………………………………………………………………………………3
3.Creating objects ofclassImage …………………………………………………………………………………….4
3.1.Attributes oftheImage object …………………………………………………………………………….4
3.2.Methods ontheImage object ……………………………………………………………………………..5
4.TheImageDraw module …………………………………………………………………………………………….8
5.Image enhancement: theImageFilter module ………………………………………………………………9
6.TheImageFont module …………………………………………………………………………………………..10
7.TheImageTk module ………………………………………………………………………………………………10
8.Supported fileformats ………………………………………………………………………………………………11
1.Introduction
The Python Imaging Library (PIL) allows you tocreate, modify, and convert image files inawide
variety offormats using thePython language.
Foradditional PILfeatures notdescribed inthisdocument, refer totheonline PILhandbook3.
Formore information about Python, refer totheauthor's companion publication, Python programming
language quick reference4,ortothePython Web site5,forgeneral information about thePython language.
1http://www.nmt.edu/tcc/help/pubs/pil/2http://www.nmt.edu/tcc/help/pubs/pil/pil.pdf3http://www.pythonware.com/library/pil/handbook/index.htm4http://www.nmt.edu/tcc/help/pubs/python22/5http://www.python.org/
1 Python Imaging Library (PIL) New Mexico Tech Computer Center
2.Definitions
These terms areused throughout:
2.1.Band
Animage band isasetofvalues, oneperimage pixel. Monochrome orgrayscale images have oneband;
color images intheRGB system have three bands, CMYK images have four, andsoon.Photoshop users
willrecognize bands assimilar toPhotoshop channels .
2.2.Modes
The mode ofanimage describes theway itrepresents colors. Each mode isrepresented byastring:
Description Bands Mode
Black andwhite (monochrome), onebitperpixel. 1 "1"
Gray scale, one8-bit byte perpixel. 1 "L"
Palette encoding: one byte perpixel, with apalette ofclassImagePalette
translating thepixels tocolors. This mode isexperimental; refer totheonline
documentation6.1 "P"
True red-green-blue color, three bytes perpixel. 3 "RGB"
True color with atransparency band, four bytes perpixel, with theAchannel
varying from 0fortransparent to255foropaque.4 "RGBA"
Cyan-magenta-yellow-black color, four bytes perpixel. 4 "CMYK"
Color video format, three 8-bit pixels. 3 "YCbCr"
32-bit integer pixels. 1 "I"
32-bit float pixels. 1 "F"
2.3.Sizes
Thesizes ofobjects intheimage aredescribed asa2-tuple(w,h),wherehistheheight inpixels and
wisthewidth.
2.4.Coor dinates
Thecoordinates ofapixel areofitsupper leftcorner. Point (0,0) istheupper leftcorner oftheimage.
Thexcoordinate increases totheright, andtheycoordinate increases downward.
When directions aregiven ascompass points such aseastorsouthwest, assume north isup,toward the
topofthedisplay.
2.5.Angles
Angles aregiven indegrees. Zero degrees isinthe+x(east) direction, andtheangle increases counter-
clockwise, intheusual Cartesian convention. Forexample, angle 45points northeast.
6http://www.pythonware.com/library/pil/handbook/index.htm
New Mexico Tech Computer Center Python Imaging Library (PIL) 2
2.6.Bboxes(bounding boxes)
Abounding boxorbbox isarectangle intheimage. Itisdefined bya4-tuple, (x0,y0,x1,y1)where (x0,
y0)isthetopleft(northwest) corner oftherectangle, and(x1,y1)isthebottom right (southeast) corner.
Generally, thearea described byabounding boxwillinclude point (x0,y0),butitwill notinclude point
(x1,y1)ortherowandcolumn ofpixels containing point (x1,y1).
Forexample, drawing anellipse inside thebounding box(0,0,5,10) willproduce anellipse 5pixels
wide and10pixels high. Theresulting ellipse willinclude pixel column 4butnotcolumn 5,andwill
alsoinclude pixel row9butnotrow10.
2.7.Colors
You canspecify colors inseveral different ways.
•Forsingle-band images, thecolor isthepixel value. Forexample, inamode"1" image, thecolor is
asingle integer, 0forblack, 1forwhite. Formode"L",itisaninteger intherange [0,255], where 0
means black and255means white.
•Formulti-band images, supply atuple with onevalue perband. Inan"RGB" image, thetuple
(255,0,0) ispure red.
•You canuseCSS-style color name strings oftheform#rrggbb ,whererrspecifies theredpart as
two hexadecimal digits,ggspecifies green, andbbblue. Forexample,"#ffff00" means yellow
(full red+fullgreen).
•Tospecify RGB pixel values indecimal, useastring oftheform"rgb(R,G,B)".Forexample,
"rgb(0,255,0)" ispure green.
•Tospecify RGB pixel values aspercentages, useastring oftheform"rgb(R%,G%,B%)".Forexample,
youcangetalight gray with"rgb(85%,85%,85%)" .
•Tospecify colors inthe hue-saturation-lightness (HSV) system, use astring ofthe form
"hsl(H,S%,L%)".
Histhehueangle indegrees: 0isred,60isyellow, 120isgreen, andsoon.
Sisthesaturation: 0%forunsaturated (gray),100% forfully saturated.
Thelightness Lis0%forblack,50% fornormal, and100% forwhite.
Forexample,"hsl(180,100%,50%)" ispure cyan.
•OnUnix systems, youcanuseanyofthestandard color names from thelocally installed setgiven in
file"/usr/lib/X11/rgb.txt" ,such as"white" ,"DodgerBlue" ,or"coral" .
2.8.Filters
Some operations thatreduce thenumber ofpixels, such ascreating athumbnail, canusedifferent filters
tocompute thenew pixel values. These include:
NEAREST
Uses thevalue ofthenearest pixel.
BILINEAR
Uses linear interpolation over a2x2setofadjacent pixels.
3 Python Imaging Library (PIL) New Mexico Tech Computer Center
BICUBIC
Uses cubic interpolation over a4x4setofpixels.
ANTIALIAS
Neighboring pixels areresampled tofind thenew pixel value.
3.Creating objects ofclassImage
Instances oftheImage class contain animage. Tousethebasic Python imaging library, import itusing
thissyntax:
importImage
These functions return anImage object:
Image.open( f)
Reads animage from afile.Theparameter fcanbeeither thename ofafile,asastring, orareadable
Python fileobject.
Image.new( mode,size,color=None)
Creates anew image ofthegiven mode (p.2)andsize(p.2).Ifacolor (p.3)isgiven, allpixels
aresettothatcolor initially; thedefault color isblack.
Image.blend( i1,i2,a)
Creates animage byblending twoimagesi1andi2.Each pixel intheoutput iscomputed from the
corresponding pixelsp1fromi1andp2fromi2using theformula (p1x(1-a)+p2xa).
Image.composite( i1,i2,mask)
Creates acomposite image from twoequal-sized imagesi1andi2,wheremask isamask image
with mode"1","L",or"RGBA" ofthesame size.
Each pixel intheoutput hasavalue given by(p1x(1-m)+p2xm),wheremisthecorresponding
pixel frommask .
Image.eval( f,i)
Creates anew image byapplying afunction ftoeach pixel ofimagei.
Function ftakes oneargument andreturns oneargument. Iftheimage hasmultiple bands,fis
applied toeach band.
Image.merge( mode,bandList )
Creates amulti-band image from multiple single-band images ofequal size. Specify themode (p.2)
ofthenew image with themode argument. ThebandList argument isasequence ofsingle-band
image objects tobecombined.
3.1.Attribut esoftheImage object
These attributes ofimage objects areavailable:
.format
Iftheimage wastaken from afile,thisattribute issettotheformat code, such as"GIF" .Iftheimage
was created within thePIL, its.format willbeNone .Seesupported formats (p.11)foralistof
theformat codes.
.mode
Themode (p.2)oftheimage, asastring.
New Mexico Tech Computer Center Python Imaging Library (PIL) 4
.size
Theimage's size(p.2)inpixels, as2-tuple (width ,height ).
.palette
Ifthemode oftheimage is"P",thisattribute willbetheimage's palette asaninstance ofclassIm-
agePalette ;otherwise itwillbeNone .
.info
Adictionary holding data associated with theimage. Theexact information depends onthesource
image format; seethesection onsupported formats (p.11)formore information.
3.2.Methods ontheImage object
Once you have created animage object using oneofthefunctions described above ,these methods
provide operations ontheimage:
.save(f,format=None)
Writes theimage toafile.Theargument fcanbethename ofthefiletobewritten, orawriteable
Python fileobject.
Theformat argument specifies thekind ofimage filetowrite. Itmust beoneoftheformat codes
shown below under supported formats (p.11),such as"JPEG" or"TIFF" .This argument isrequired
iffisafileobject. Iffisafilename, thisargument canbeomitted, inwhich case theformat isde-
termined byinspecting theextension ofthefilename. Forexample, ifthefilename islogo.jpg ,
thefilewillbewritten inJPEG format.
.convert( mode)
Returns anew image with adifferent mode (p.2).Forexample, ifimageimhasmode"RGB" ,you
cangetanew image with mode"CMYK" using theexpression im.convert("CMYK") .
.copy()
Returns acopy oftheimage.
.crop(bbox)
Returns anew image containing thebounding box(p.3)specified bybbox intheoriginal. The
rows andcolumns specified bythethird andfourth values ofbbox will notbeincluded. Forexample,
ifimageimhassize4x4,im.crop((0,0,3,3)) willhave size3x3.
.filter( name)
Return acopy oftheimage filtered through anamed image enhancement filter. Seeimage filter (p.9)
foralistofthepredefined image enhancement filters.
.getbands()
Returns asequence ofstrings, oneperband, representing themode (p.2)oftheimage. Forexample,
ifimageimhasmode"RGB" ,im.getbands() willreturn('R','G','B') .
.getbbox()
Returns thesmallest bounding box(p.3)thatencloses thenonzero parts oftheimage.
.getextrema()
Forsingle-band images, returns atuple(min,max)whereministhesmallest pixel value andmax
thelargest pixel value intheimage.
Formulti-band images, returns atuple containing the(min,max)tuple foreach band.
5 Python Imaging Library (PIL) New Mexico Tech Computer Center
.getpixel( xy)
Returns thepixel value orvalues atthegiven coordinates (p.2).Forsingle-band images, returns
asingle number; asequence ofpixel values isreturned formulti-band images. Forexample, ifthe
topleftpixel ofanimageimofmode"L"hasvalue 128,thenim.getpixel((0,0)) returns 128.
.histogram( mask=None)
Forsingle-band images, returns alistofvalues[c0,c1,…] whereciisthenumber ofpixels
with valuei.
Formulti-band images, returns asingle sequence thatistheconcatenation ofthesequences forall
bands.
Togetahistogram ofselected pixels from theimage, build asame-sized mask image ofmode"1"
or"L" andpass ittothismethod asanargument. Theresulting histogram data willinclude only
those pixels from theimage thatcorrespond tononzero pixels inthemask argument.
.offset( dx,dy=None)
Returns anew image thesame sizeastheoriginal, butwith allpixels rotateddxinthe+xdirection,
anddyinthe+ydirection. Pixels willwrap around. Ifdyisomitted, itdefaults tothesame value
asdx.
Forexample, ifimisanimage ofsize4x4,then inthenew imageim.offset(2,1) ,thepixel that
wasat(1,1) willnow beat(3,2) .Wrapping around, thepixel thatwasat(3,3) willnow beat
(0,1) .
.paste( i2,where,mask=None)
Pixels arereplaced with thepixels from imagei2.
•Ifwhere isapair ofcoordinates (p.2)(x,y),thenew pixels arepasted sothatthe(0,0) pixel of
i2pixel replaces the(x,y)pixel, with theother pixels ofi2pasted incorresponding positions.
Pixels fromi2thatfalloutside theoriginal arediscarded.
•Ifwhere isabounding box(p.3),i2must have thesame sizeasthat bbox, andreplaces the
pixels atthatbbox's position.
•Ifwhere isNone ,imagei2must bethesame sizeastheoriginal, andreplaces theentire original.
Ifthemode ofi2isdifferent, itisconverted before pasting.
Ifamask argument issupplied, itisused tocontrol which pixels getreplaced. Themask argument
must beanimage ofthesame sizeastheoriginal.
•Ifthemask hasmode"1",original pixels areleftalone where there are0pixels inthemask, but
replaced where themask haspixels ofvalue 1.
•Ifthemask hasmode"L",original pixels areleftalone where there are0pixels inthemask, and
replaced where themask has255pixels. Intermediate values interpolate between thepixel values
oftheoriginal andreplacement images.
•Ifthemask has"RGBA" mode, its"A" band isused inthesame way asan"L"-mode mask.
.paste( color,box=None,mask=None)
Setsmultiple pixels tothesame color. Iftheboxargument isomitted, theentire image issettothat
color. Ifpresent, itmust beabounding box(p.3),andtherectangle defined bythatbbox issetto
thatcolor.
Ifamask issupplied, itselects thepixels tobereplaced asintheprevious form ofthe.paste()
method, above.
.point( function )
Returns anew image with each pixel modified. Toapply afunction f(x) toeach pixel, callthis
method withfasthefirstargument. Thefunction should operate onasingle pixel value (0to255)
andreturn thenew pixel value.
New Mexico Tech Computer Center Python Imaging Library (PIL) 6
.point( table)
Totranslate pixels using atable lookup, pass that table asasequence tothefirst argument. The
table should beasequence of256nvalues, wherenisthenumber ofbands intheimage. Each pixel
inbandboftheimage isreplaced bythevalue fromtable[p+256*b],wherepistheoldpixel's
value inthatband.
.putalpha( band)
Toaddanalpha (transparency) band toan"RGBA" -mode image, callthismethod andpass itan
image ofthesame sizehaving mode"L" or"1".Thepixels oftheband image replace thealpha
band oftheoriginal image inplace.
.putpixel( xy,color)
Replaces onepixel oftheimage atcoordinates (p.2)xy.Forsingle-band images, specify thecolor
asasingle pixel value; formulti-band images, provide asequence containing thepixel values of
each band.
Forexample,im.putpixel((0,0), (0,255,0)) would setthetopleftpixel ofanRGB image
imtogreen.
Replacing many pixels with thismethod may beslow. Refer totheImageDraw module forfaster
techniques forpixel modification.
.resize( size,filter=None)
Returns anew image ofthegivensize bylinear stretching orshrinking oftheoriginal image. You
may provide afilter (p.3)tospecify how theinterpolation isdone; thedefault isNEAREST .
.rotate( theta)
Returns anew image rotated around itscenter bytheta degrees. Any pixels thatarenotcovered
byrotation oftheoriginal image aresettoblack.
.show()
OnUnix systems, thismethod runs thexvimage viewer todisplay theimage. OnWindows boxes,
theimage issaved inBMP format andcanbeviewed using Paint. This canbeuseful fordebugging.
.split()
Returns atuple containing each band oftheoriginal image asanimage ofmode"L".Forexample,
applying thismethod toan"RGB" image produces atuple ofthree images, oneeach forthered,
green, andblue bands.
.thumbnail( size,filter=None)
Replaces theoriginal image, inplace, with anew image ofthegiven size (p.2).The optional
filter argument works inthesame way asinthe.resize() method.
Theaspect ratio (height :width) ispreserved bythisoperation. Theresulting image willbeaslarge
aspossible while stillfitting within thegiven size. Forexample, ifimageimhassize(400,150), its
sizeafterim.thumbnail((40,40)) willbe(40,15).
.transform( xs,ys,Image.EXTENT, (x0,y0,x1,y1))
Returns atransformed copy oftheimage. Inthetransformed image, thepoint originally at(x0,y0)
willappear at(0,0), andpoint (x1,y1)willappear at(xs,ys).
.transform( xs,ys,Image.AFFINE, (a,b,c,d,e,f))
Affine transformation. Thevaluesathrough farethefirsttworows ofanaffine transform matrix.
Each pixel at(x,y)intheresulting image comes from position (ax+by+c,dx+ey+f)intheinput
image, rounded tothenearest pixel.
.transpose( method)
Return aflipped orrotated copy oftheoriginal image. Themethod canbeanyof:
•Image.FLIP_RIGHT_LEFT toreflect around thevertical centerline.
7 Python Imaging Library (PIL) New Mexico Tech Computer Center
•Image.FLIP_TOP_BOTTOM toreflect around thehorizontal centerline.
•Image.ROTATE_90 torotate theimage 90degrees clockwise.
•Image.ROTATE_180 torotate theimage 180degrees.
•Image.ROTATE_270 torotate theimage clockwise by270degrees.
4.TheImageDraw module
When youneed todraw onanimage, import theImageDraw module likethis:
importImageDraw
Then instantiate aDraw object:
draw=ImageDraw.Draw( i)
whereiistheImage object youwant todraw on.
Methods onaDraw object include:
.arc(bbox,start,end,fill=None)
Draws anarc,thatpart oftheellipse fitting inside thebounding box(p.3)bbox andlying between
anglesstart andend.Note:Angles increase clockwise, unlike angles elsewhere inthePIL. For
example,draw.arc((0,0,200,200), 0,135) would draw acircular arccentered at(100,100)
andextending from theeasttothesouthwest.
Ifsupplied, thefill argument specifies thecolor ofthearc.Thedefault color iswhite.
.chord( bbox,start,end,fill=None,outline=None)
Same asthe.arc() method, butitalsodraws astraight lineconnecting theendpoints ofthearc.
Forthismethod, thefill argument determines thecolor inside, thatis,between thechord andthe
arc.Thedefault isthatthisarea isnotfilled.
Tochange thecolor oftheperimeter border around thechord's area, settheoutline argument to
thecolor youwant. Thedefault color iswhite.
.ellipse( bbox,fill=None,outline=None)
Draws theellipse thatfitsinside thebounding box(p.3)bbox .Todraw acircle, useasquare
bounding box.
Note thattheellipse willinclude theleftandtopsides ofthebounding box, butthey will exclude
theright andbottom sides ofthebox. Forexample, abounding box(0,0,10,10) willgive youa
circle ofdiameter 10,notdiameter 11.
Ifyouomit thefill argument, only theperimeter oftheellipse isdrawn. Ifyoupass acolor to
thisargument, theinterior oftheellipse willbefilled with thatcolor.
Useoutline=ctodraw theperimeter border using colorc.Thedefault color iswhite.
.line(L,fill=None)
Draws oneormore linesegments. Theargument Lspecifies theendpoints, andcanhave either of
these forms:
•Asequence of2-element sequences, each ofwhich specifies one endpoint. For example,
draw.line([(10,20),(100,20)] would draw astraight linefrom (10,20) to(100,20). You
canspecify anynumber ofpoints togeta“polyline;” forexample,draw.line(((60,60),
(90,60), (90,90), (60,90), (60,60))) would draw asquare 30pixels onaside.
New Mexico Tech Computer Center Python Imaging Library (PIL) 8
•Asequence containing aneven number ofvalues. Each succeeding pairistaken asan(x,y) co-
ordinate. Forexample,draw.line((10,20,100,20)) would give youthesame result asthe
firstexample intheparagraph above.
.pieslice( bbox,start,end,fill=None,outline=None)
Similar tothe.arc() method, butdraws tworadii connecting theendpoints ofthearctothecenter.
Thefill andoutline arguments work inthesame way asinthe.chord() method: fill de-
termines theinterior color, andoutline setsthecolor oftheborder.
.point( xy,fill=None)
Sets thepixel atcoordinates (p.2)xytothecolor specified bythefill argument. Thedefault
color iswhite.
.polygon( L,fill=None, outline=None)
Works likethe.line() method, butafter drawing allthespecified linesegments, itdraws one
more thatconnects thelastpoint back tothefirst. Theinterior displays thefill ,transparent by
default. Theborder isdrawn intheoutline color, defaulting towhite.
Forexample,draw.polygon([(60,60), (90,60), (90,90), (60,90)], fill="red",
outline="green") would draw asquare boxwith agreen outline, filled with red.
.text(xy,message,fill=None,font=None)
Draws thetextofthestringmessage ontheimage with itsupper leftcorner atcoordinates (p.2)
xy.
Towrite thetextincolor, pass thatcolor tothefill argument; thedefault textcolor iswhite.
There isadefault font, rather small (about 11pixels tall)andinaserif style. You canalsospecify a
fontusing thefont argument; seetheImageFont module formore information onfonts.
.textsize( message,font=None)
Foragiven textstringmessage ,returns atuple(w,h)wherewisthewidth inpixels thattextwill
occupy onthedisplay, andhitstheheight inpixels.
Ifthefont argument isomitted, youwillgetthesizeusing thedefault font. Supply afont tothis
method's font argument togetthesizeofthetextinthatfont.
5.Imageenhanc ement: theImageFilter module
Certain operations allow youtofilter theimage data using oneofasetofpredefined filters. Usethis
form ofimport:
importImageFilter
Once youhave imported themodule, youcanuseanyofthese filters:
•ImageFilter.BLUR
•ImageFilter.CONTOUR
•ImageFilter.DETAIL
•ImageFilter.EDGE_ENHANCE
•ImageFilter.EDGE_ENHANCE_MORE
•ImageFilter.EMBOSS
•ImageFilter.FIND_EDGES
•ImageFilter.SMOOTH
•ImageFilter.SMOOTH_MORE
•ImageFilter.SHARPEN
9 Python Imaging Library (PIL) New Mexico Tech Computer Center
6.TheImageFont module
Tospecify fonts forthe.text() method from theImageDraw module, import thismodule:
importImageFont
You canthen create afontobject from anyTrueType fontbyusing thisfunction:
ImageFont.truetype( file,size)
Returns afontobject representing theTrueType fontwhose filename isgiven bythefile argument,
with afontheight ofsize pixels.
Methods onfontobjects include:
.getsize( text)
Foragiven stringtext ,returns atuple(w,h)wherewisthewidth inpixels thattextwilloccupy
onthedisplay, andhitstheheight inpixels.
OnUnix systems locally, TrueType fonts canbefound inthisdirectory:
/usr/share/fonts/
Atthiswriting, there were twofamilies ofpublic-domain fonts:
•Deja Vufonts:/usr/share/fonts/dejavu-lgc/ .
•Liberation fonts:/usr/share/fonts/liberation/ .
Here's acomplete program thatcreates a200x50 gray image, writes textonitinred,andsaves ittofile
runaway.jpg .FileDejaVuLGCSansCondensed-Bold.ttf issans-serif, condensed, bold fontinthe
Deja Vufamily.
#!/usr/local/bin/python
importImage
importImageDraw
importImageFont
fontPath ="/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16 =ImageFont.truetype (fontPath, 16)
im=Image.new ("RGB",(200,50), "#ddd")
draw=ImageDraw.Draw (im)
draw.text ((10,10), "Runawayyyy!", font=sans16, fill="red" )
im.save ("runaway.jpg" )
OnWindows systems, look inC:\WINDOWS\Fonts .
7.TheImageTk module
This module isforusewith thegraphical user interface functions oftheTkinter package. Formore in-
formation about theTkinter widget set,seethelocal Tkinter page7.
Toimport theImageTk module:
importImageTk
7http://www.nmt.edu/tcc/help/lang/python/tkinter.html
New Mexico Tech Computer Center Python Imaging Library (PIL) 10
This module contains twoclass constructors:
ImageTk.BitmapImage( i,**options)
Given animagei,constructs aBitMapImage object thatcanbeused wherever Tkinter expects an
image object. Theimage must have mode"1".Any keyword options arepassed ontoTkinter.
Forexample, theoptionforeground= ccanbeused todisplay thepixels ofvalue 1incolorc,
while pixels ofvalue 0aretransparent.
ImageTk.PhotoImage( i)
Given animagei,constructs aPhotoImage object thatcanbeused wherever Tkinter expects an
image object.
Warning
There isabuginthecurrent version ofthePython Imaging Library thatcancause your images notto
display properly. When youcreate anobject ofclassPhotoImage ,thereference count forthatobject
does notgetproperly incremented, sounless youkeep areference tothatobject somewhere else, the
PhotoImage object may begarbage-collected, leaving your graphic blank ontheapplication.
Forexample, ifyouhave acanvas orlabel widget thatrefers tosuch animage object, keep alistnamed
.imageList inthatobject, andappend allPhotoImage objects toitasthey arecreated. Ifyour widget
may cycle through alarge number ofimages, youwillalsowant todelete theobjects from thislistwhen
they arenolonger inuse.
ImageTk.PhotoImage( mode,size)
Creates anemptyPhotoImage object with thegiven mode (p.2)andsize(p.2).
Tochange image data inaPhotoImage object, usethismethod:
.paste( i2,bbox=None)
Image data from anImage objecti2ispasted intothePhotoImage object. Topaste thenew data
into agiven location, specify thebbox argument asabounding box(p.3);thisargument canbe
omitted ifi2isthesame sizeasthePhotoImage object.
8.Suppor tedfileforma ts
These arethekinds ofimage files supported bythePIL. Thefirstcolumn gives thePILfiletype code,
asused intheImage.format attribute andtheImage.save() method (although notalltypes can
besaved). Thesecond column shows thefileextensions associated with thattype. Thenext twocolumns
show which modes canberead (ifany) andwritten (ifany), ortheword “None” ifthatfiletype cannot
beread orwritten.
Remarks Write modes Read modes Extensions Type
1LPRGB 1LPRGB .bmp.dib "BMP"
Fax format. Only thefirst image is
read.None 1LPRGB .dcx"DCX"
Encapsulated PostScript LRGB None .eps.ps "EPS"
P P .gif"GIF"
Used byLabEye and other applica-
tions.All All .im"IM"
11 Python Imaging Library (PIL) New Mexico Tech Computer Center
Remarks Write modes Read modes Extensions Type
LRGBCMYK LRGBCMYK .jpg.jpe
.jpeg"JPEG"
Photo CDformat; willread the768x512
resolution.None RGB .pcd"PCD"
1LPRGB 1LPRGB .pcx"PCX"
Adobe Page Description Format. 1RGB None .pdf"PDF"
Portable Network Graphics format. 1LPRGBRGBA 1LPRGBRGBA .png"PNG"
1LRGB 1LRGB .pbm.pgm
.ppm"PPM"
Photoshop format. None P .psd"PSD"
1LRGBCMYK 1LRGBCMYK .tif.tiff "TIFF"
Xbitmap files. 1 1 .xbm"XBM"
Xpixmap files with upto256colors. P P .xpm"XPM"
This table includes only some ofthemore common image formats. Refer totheonline documentation8
forafulllist.
8http://www.pythonware.com/library/pil/handbook/index.htm
New Mexico Tech Computer Center Python Imaging Library (PIL) 12
Copyright Notice
© Licențiada.org respectă drepturile de proprietate intelectuală și așteaptă ca toți utilizatorii să facă același lucru. Dacă consideri că un conținut de pe site încalcă drepturile tale de autor, te rugăm să trimiți o notificare DMCA.
Acest articol: Python Imaging Library (PIL) [613950] (ID: 613950)
Dacă considerați că acest conținut vă încalcă drepturile de autor, vă rugăm să depuneți o cerere pe pagina noastră Copyright Takedown.
