_imaging.c 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430
  1. /*
  2. * The Python Imaging Library.
  3. *
  4. * the imaging library bindings
  5. *
  6. * history:
  7. * 1995-09-24 fl Created
  8. * 1996-03-24 fl Ready for first public release (release 0.0)
  9. * 1996-03-25 fl Added fromstring (for Jack's "img" library)
  10. * 1996-03-28 fl Added channel operations
  11. * 1996-03-31 fl Added point operation
  12. * 1996-04-08 fl Added new/new_block/new_array factories
  13. * 1996-04-13 fl Added decoders
  14. * 1996-05-04 fl Added palette hack
  15. * 1996-05-12 fl Compile cleanly as C++
  16. * 1996-05-19 fl Added matrix conversions, gradient fills
  17. * 1996-05-27 fl Added display_mode
  18. * 1996-07-22 fl Added getbbox, offset
  19. * 1996-07-23 fl Added sequence semantics
  20. * 1996-08-13 fl Added logical operators, point mode
  21. * 1996-08-16 fl Modified paste interface
  22. * 1996-09-06 fl Added putdata methods, use abstract interface
  23. * 1996-11-01 fl Added xbm encoder
  24. * 1996-11-04 fl Added experimental path stuff, draw_lines, etc
  25. * 1996-12-10 fl Added zip decoder, crc32 interface
  26. * 1996-12-14 fl Added modulo arithmetics
  27. * 1996-12-29 fl Added zip encoder
  28. * 1997-01-03 fl Added fli and msp decoders
  29. * 1997-01-04 fl Added experimental sun_rle and tga_rle decoders
  30. * 1997-01-05 fl Added gif encoder, getpalette hack
  31. * 1997-02-23 fl Added histogram mask
  32. * 1997-05-12 fl Minor tweaks to match the IFUNC95 interface
  33. * 1997-05-21 fl Added noise generator, spread effect
  34. * 1997-06-05 fl Added mandelbrot generator
  35. * 1997-08-02 fl Modified putpalette to coerce image mode if necessary
  36. * 1998-01-11 fl Added INT32 support
  37. * 1998-01-22 fl Fixed draw_points to draw the last point too
  38. * 1998-06-28 fl Added getpixel, getink, draw_ink
  39. * 1998-07-12 fl Added getextrema
  40. * 1998-07-17 fl Added point conversion to arbitrary formats
  41. * 1998-09-21 fl Added support for resampling filters
  42. * 1998-09-22 fl Added support for quad transform
  43. * 1998-12-29 fl Added support for arcs, chords, and pieslices
  44. * 1999-01-10 fl Added some experimental arrow graphics stuff
  45. * 1999-02-06 fl Added draw_bitmap, font acceleration stuff
  46. * 2001-04-17 fl Fixed some egcs compiler nits
  47. * 2001-09-17 fl Added screen grab primitives (win32)
  48. * 2002-03-09 fl Added stretch primitive
  49. * 2002-03-10 fl Fixed filter handling in rotate
  50. * 2002-06-06 fl Added I, F, and RGB support to putdata
  51. * 2002-06-08 fl Added rankfilter
  52. * 2002-06-09 fl Added support for user-defined filter kernels
  53. * 2002-11-19 fl Added clipboard grab primitives (win32)
  54. * 2002-12-11 fl Added draw context
  55. * 2003-04-26 fl Tweaks for Python 2.3 beta 1
  56. * 2003-05-21 fl Added createwindow primitive (win32)
  57. * 2003-09-13 fl Added thread section hooks
  58. * 2003-09-15 fl Added expand helper
  59. * 2003-09-26 fl Added experimental LA support
  60. * 2004-02-21 fl Handle zero-size images in quantize
  61. * 2004-06-05 fl Added ptr attribute (used to access Imaging objects)
  62. * 2004-06-05 fl Don't crash when fetching pixels from zero-wide images
  63. * 2004-09-17 fl Added getcolors
  64. * 2004-10-04 fl Added modefilter
  65. * 2005-10-02 fl Added access proxy
  66. * 2006-06-18 fl Always draw last point in polyline
  67. *
  68. * Copyright (c) 1997-2006 by Secret Labs AB
  69. * Copyright (c) 1995-2006 by Fredrik Lundh
  70. *
  71. * See the README file for information on usage and redistribution.
  72. */
  73. #define PY_SSIZE_T_CLEAN
  74. #include "Python.h"
  75. #ifdef HAVE_LIBJPEG
  76. #include "jconfig.h"
  77. #endif
  78. #ifdef HAVE_LIBZ
  79. #include "zlib.h"
  80. #endif
  81. #ifdef HAVE_LIBTIFF
  82. #ifndef _TIFFIO_
  83. #include <tiffio.h>
  84. #endif
  85. #endif
  86. #include "libImaging/Imaging.h"
  87. #define _USE_MATH_DEFINES
  88. #include <math.h>
  89. /* Configuration stuff. Feel free to undef things you don't need. */
  90. #define WITH_IMAGECHOPS /* ImageChops support */
  91. #define WITH_IMAGEDRAW /* ImageDraw support */
  92. #define WITH_MAPPING /* use memory mapping to read some file formats */
  93. #define WITH_IMAGEPATH /* ImagePath stuff */
  94. #define WITH_ARROW /* arrow graphics stuff (experimental) */
  95. #define WITH_EFFECTS /* special effects */
  96. #define WITH_QUANTIZE /* quantization support */
  97. #define WITH_RANKFILTER /* rank filter */
  98. #define WITH_MODEFILTER /* mode filter */
  99. #define WITH_THREADING /* "friendly" threading support */
  100. #define WITH_UNSHARPMASK /* Kevin Cazabon's unsharpmask module */
  101. #undef VERBOSE
  102. #define B16(p, i) ((((int)p[(i)]) << 8) + p[(i) + 1])
  103. #define L16(p, i) ((((int)p[(i) + 1]) << 8) + p[(i)])
  104. #define S16(v) ((v) < 32768 ? (v) : ((v)-65536))
  105. /* -------------------------------------------------------------------- */
  106. /* OBJECT ADMINISTRATION */
  107. /* -------------------------------------------------------------------- */
  108. typedef struct {
  109. PyObject_HEAD Imaging image;
  110. ImagingAccess access;
  111. } ImagingObject;
  112. static PyTypeObject Imaging_Type;
  113. #ifdef WITH_IMAGEDRAW
  114. typedef struct {
  115. /* to write a character, cut out sxy from glyph data, place
  116. at current position plus dxy, and advance by (dx, dy) */
  117. int dx, dy;
  118. int dx0, dy0, dx1, dy1;
  119. int sx0, sy0, sx1, sy1;
  120. } Glyph;
  121. typedef struct {
  122. PyObject_HEAD ImagingObject *ref;
  123. Imaging bitmap;
  124. int ysize;
  125. int baseline;
  126. Glyph glyphs[256];
  127. } ImagingFontObject;
  128. static PyTypeObject ImagingFont_Type;
  129. typedef struct {
  130. PyObject_HEAD ImagingObject *image;
  131. UINT8 ink[4];
  132. int blend;
  133. } ImagingDrawObject;
  134. static PyTypeObject ImagingDraw_Type;
  135. #endif
  136. typedef struct {
  137. PyObject_HEAD ImagingObject *image;
  138. int readonly;
  139. } PixelAccessObject;
  140. static PyTypeObject PixelAccess_Type;
  141. PyObject *
  142. PyImagingNew(Imaging imOut) {
  143. ImagingObject *imagep;
  144. if (!imOut) {
  145. return NULL;
  146. }
  147. imagep = PyObject_New(ImagingObject, &Imaging_Type);
  148. if (imagep == NULL) {
  149. ImagingDelete(imOut);
  150. return NULL;
  151. }
  152. #ifdef VERBOSE
  153. printf("imaging %p allocated\n", imagep);
  154. #endif
  155. imagep->image = imOut;
  156. imagep->access = ImagingAccessNew(imOut);
  157. return (PyObject *)imagep;
  158. }
  159. static void
  160. _dealloc(ImagingObject *imagep) {
  161. #ifdef VERBOSE
  162. printf("imaging %p deleted\n", imagep);
  163. #endif
  164. if (imagep->access) {
  165. ImagingAccessDelete(imagep->image, imagep->access);
  166. }
  167. ImagingDelete(imagep->image);
  168. PyObject_Del(imagep);
  169. }
  170. #define PyImaging_Check(op) (Py_TYPE(op) == &Imaging_Type)
  171. Imaging
  172. PyImaging_AsImaging(PyObject *op) {
  173. if (!PyImaging_Check(op)) {
  174. PyErr_BadInternalCall();
  175. return NULL;
  176. }
  177. return ((ImagingObject *)op)->image;
  178. }
  179. /* -------------------------------------------------------------------- */
  180. /* THREAD HANDLING */
  181. /* -------------------------------------------------------------------- */
  182. void
  183. ImagingSectionEnter(ImagingSectionCookie *cookie) {
  184. #ifdef WITH_THREADING
  185. *cookie = (PyThreadState *)PyEval_SaveThread();
  186. #endif
  187. }
  188. void
  189. ImagingSectionLeave(ImagingSectionCookie *cookie) {
  190. #ifdef WITH_THREADING
  191. PyEval_RestoreThread((PyThreadState *)*cookie);
  192. #endif
  193. }
  194. /* -------------------------------------------------------------------- */
  195. /* BUFFER HANDLING */
  196. /* -------------------------------------------------------------------- */
  197. /* Python compatibility API */
  198. int
  199. PyImaging_CheckBuffer(PyObject *buffer) {
  200. return PyObject_CheckBuffer(buffer);
  201. }
  202. int
  203. PyImaging_GetBuffer(PyObject *buffer, Py_buffer *view) {
  204. /* must call check_buffer first! */
  205. return PyObject_GetBuffer(buffer, view, PyBUF_SIMPLE);
  206. }
  207. /* -------------------------------------------------------------------- */
  208. /* EXCEPTION REROUTING */
  209. /* -------------------------------------------------------------------- */
  210. /* error messages */
  211. static const char *must_be_sequence = "argument must be a sequence";
  212. static const char *must_be_two_coordinates =
  213. "coordinate list must contain exactly 2 coordinates";
  214. static const char *incorrectly_ordered_x_coordinate =
  215. "x1 must be greater than or equal to x0";
  216. static const char *incorrectly_ordered_y_coordinate =
  217. "y1 must be greater than or equal to y0";
  218. static const char *wrong_mode = "unrecognized image mode";
  219. static const char *wrong_raw_mode = "unrecognized raw mode";
  220. static const char *outside_image = "image index out of range";
  221. static const char *outside_palette = "palette index out of range";
  222. static const char *wrong_palette_size = "invalid palette size";
  223. static const char *no_palette = "image has no palette";
  224. static const char *readonly = "image is readonly";
  225. /* static const char* no_content = "image has no content"; */
  226. void *
  227. ImagingError_OSError(void) {
  228. PyErr_SetString(PyExc_OSError, "error when accessing file");
  229. return NULL;
  230. }
  231. void *
  232. ImagingError_MemoryError(void) {
  233. return PyErr_NoMemory();
  234. }
  235. void *
  236. ImagingError_Mismatch(void) {
  237. PyErr_SetString(PyExc_ValueError, "images do not match");
  238. return NULL;
  239. }
  240. void *
  241. ImagingError_ModeError(void) {
  242. PyErr_SetString(PyExc_ValueError, "image has wrong mode");
  243. return NULL;
  244. }
  245. void *
  246. ImagingError_ValueError(const char *message) {
  247. PyErr_SetString(
  248. PyExc_ValueError, (message) ? (char *)message : "unrecognized argument value");
  249. return NULL;
  250. }
  251. void
  252. ImagingError_Clear(void) {
  253. PyErr_Clear();
  254. }
  255. /* -------------------------------------------------------------------- */
  256. /* HELPERS */
  257. /* -------------------------------------------------------------------- */
  258. static int
  259. getbands(const char *mode) {
  260. Imaging im;
  261. int bands;
  262. /* FIXME: add primitive to libImaging to avoid extra allocation */
  263. im = ImagingNew(mode, 0, 0);
  264. if (!im) {
  265. return -1;
  266. }
  267. bands = im->bands;
  268. ImagingDelete(im);
  269. return bands;
  270. }
  271. #define TYPE_UINT8 (0x100 | sizeof(UINT8))
  272. #define TYPE_INT32 (0x200 | sizeof(INT32))
  273. #define TYPE_FLOAT16 (0x500 | sizeof(FLOAT16))
  274. #define TYPE_FLOAT32 (0x300 | sizeof(FLOAT32))
  275. #define TYPE_DOUBLE (0x400 | sizeof(double))
  276. static void *
  277. getlist(PyObject *arg, Py_ssize_t *length, const char *wrong_length, int type) {
  278. /* - allocates and returns a c array of the items in the
  279. python sequence arg.
  280. - the size of the returned array is in length
  281. - all of the arg items must be numeric items of the type
  282. specified in type
  283. - sequence length is checked against the length parameter IF
  284. an error parameter is passed in wrong_length
  285. - caller is responsible for freeing the memory
  286. */
  287. Py_ssize_t i, n;
  288. int itemp;
  289. double dtemp;
  290. FLOAT32 ftemp;
  291. UINT8 *list;
  292. PyObject *seq;
  293. PyObject *op;
  294. if (!PySequence_Check(arg)) {
  295. PyErr_SetString(PyExc_TypeError, must_be_sequence);
  296. return NULL;
  297. }
  298. n = PySequence_Size(arg);
  299. if (length && wrong_length && n != *length) {
  300. PyErr_SetString(PyExc_ValueError, wrong_length);
  301. return NULL;
  302. }
  303. /* malloc check ok, type & ff is just a sizeof(something)
  304. calloc checks for overflow */
  305. list = calloc(n, type & 0xff);
  306. if (!list) {
  307. return ImagingError_MemoryError();
  308. }
  309. seq = PySequence_Fast(arg, must_be_sequence);
  310. if (!seq) {
  311. free(list);
  312. return NULL;
  313. }
  314. for (i = 0; i < n; i++) {
  315. op = PySequence_Fast_GET_ITEM(seq, i);
  316. // DRY, branch prediction is going to work _really_ well
  317. // on this switch. And 3 fewer loops to copy/paste.
  318. switch (type) {
  319. case TYPE_UINT8:
  320. itemp = PyLong_AsLong(op);
  321. list[i] = CLIP8(itemp);
  322. break;
  323. case TYPE_INT32:
  324. itemp = PyLong_AsLong(op);
  325. memcpy(list + i * sizeof(INT32), &itemp, sizeof(itemp));
  326. break;
  327. case TYPE_FLOAT32:
  328. ftemp = (FLOAT32)PyFloat_AsDouble(op);
  329. memcpy(list + i * sizeof(ftemp), &ftemp, sizeof(ftemp));
  330. break;
  331. case TYPE_DOUBLE:
  332. dtemp = PyFloat_AsDouble(op);
  333. memcpy(list + i * sizeof(dtemp), &dtemp, sizeof(dtemp));
  334. break;
  335. }
  336. }
  337. Py_DECREF(seq);
  338. if (PyErr_Occurred()) {
  339. free(list);
  340. return NULL;
  341. }
  342. if (length) {
  343. *length = n;
  344. }
  345. return list;
  346. }
  347. FLOAT32
  348. float16tofloat32(const FLOAT16 in) {
  349. UINT32 t1;
  350. UINT32 t2;
  351. UINT32 t3;
  352. FLOAT32 out[1] = {0};
  353. t1 = in & 0x7fff; // Non-sign bits
  354. t2 = in & 0x8000; // Sign bit
  355. t3 = in & 0x7c00; // Exponent
  356. t1 <<= 13; // Align mantissa on MSB
  357. t2 <<= 16; // Shift sign bit into position
  358. t1 += 0x38000000; // Adjust bias
  359. t1 = (t3 == 0 ? 0 : t1); // Denormals-as-zero
  360. t1 |= t2; // Re-insert sign bit
  361. memcpy(out, &t1, 4);
  362. return out[0];
  363. }
  364. static inline PyObject *
  365. getpixel(Imaging im, ImagingAccess access, int x, int y) {
  366. union {
  367. UINT8 b[4];
  368. UINT16 h;
  369. INT32 i;
  370. FLOAT32 f;
  371. } pixel;
  372. if (x < 0) {
  373. x = im->xsize + x;
  374. }
  375. if (y < 0) {
  376. y = im->ysize + y;
  377. }
  378. if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
  379. PyErr_SetString(PyExc_IndexError, outside_image);
  380. return NULL;
  381. }
  382. access->get_pixel(im, x, y, &pixel);
  383. switch (im->type) {
  384. case IMAGING_TYPE_UINT8:
  385. switch (im->bands) {
  386. case 1:
  387. return PyLong_FromLong(pixel.b[0]);
  388. case 2:
  389. return Py_BuildValue("BB", pixel.b[0], pixel.b[1]);
  390. case 3:
  391. return Py_BuildValue("BBB", pixel.b[0], pixel.b[1], pixel.b[2]);
  392. case 4:
  393. return Py_BuildValue(
  394. "BBBB", pixel.b[0], pixel.b[1], pixel.b[2], pixel.b[3]);
  395. }
  396. break;
  397. case IMAGING_TYPE_INT32:
  398. return PyLong_FromLong(pixel.i);
  399. case IMAGING_TYPE_FLOAT32:
  400. return PyFloat_FromDouble(pixel.f);
  401. case IMAGING_TYPE_SPECIAL:
  402. if (im->bands == 1) {
  403. return PyLong_FromLong(pixel.h);
  404. } else {
  405. return Py_BuildValue("BBB", pixel.b[0], pixel.b[1], pixel.b[2]);
  406. }
  407. break;
  408. }
  409. /* unknown type */
  410. Py_INCREF(Py_None);
  411. return Py_None;
  412. }
  413. static char *
  414. getink(PyObject *color, Imaging im, char *ink) {
  415. int g = 0, b = 0, a = 0;
  416. double f = 0;
  417. /* Windows 64 bit longs are 32 bits, and 0xFFFFFFFF (white) is a
  418. Python long (not int) that raises an overflow error when trying
  419. to return it into a 32 bit C long
  420. */
  421. PY_LONG_LONG r = 0;
  422. FLOAT32 ftmp;
  423. INT32 itmp;
  424. /* fill ink buffer (four bytes) with something that can
  425. be cast to either UINT8 or INT32 */
  426. int rIsInt = 0;
  427. int tupleSize = PyTuple_Check(color) ? PyTuple_GET_SIZE(color) : -1;
  428. if (tupleSize == 1) {
  429. color = PyTuple_GetItem(color, 0);
  430. }
  431. if (im->type == IMAGING_TYPE_UINT8 || im->type == IMAGING_TYPE_INT32 ||
  432. im->type == IMAGING_TYPE_SPECIAL) {
  433. if (PyLong_Check(color)) {
  434. r = PyLong_AsLongLong(color);
  435. if (r == -1 && PyErr_Occurred()) {
  436. return NULL;
  437. }
  438. rIsInt = 1;
  439. } else if (im->bands == 1) {
  440. PyErr_SetString(
  441. PyExc_TypeError, "color must be int or single-element tuple");
  442. return NULL;
  443. } else if (tupleSize == -1) {
  444. PyErr_SetString(PyExc_TypeError, "color must be int or tuple");
  445. return NULL;
  446. }
  447. }
  448. switch (im->type) {
  449. case IMAGING_TYPE_UINT8:
  450. /* unsigned integer */
  451. if (im->bands == 1) {
  452. /* unsigned integer, single layer */
  453. if (rIsInt != 1) {
  454. if (tupleSize != 1) {
  455. PyErr_SetString(PyExc_TypeError, "color must be int or single-element tuple");
  456. return NULL;
  457. } else if (!PyArg_ParseTuple(color, "L", &r)) {
  458. return NULL;
  459. }
  460. }
  461. ink[0] = (char)CLIP8(r);
  462. ink[1] = ink[2] = ink[3] = 0;
  463. } else {
  464. if (rIsInt) {
  465. /* compatibility: ABGR */
  466. a = (UINT8)(r >> 24);
  467. b = (UINT8)(r >> 16);
  468. g = (UINT8)(r >> 8);
  469. r = (UINT8)r;
  470. } else {
  471. a = 255;
  472. if (im->bands == 2) {
  473. if (tupleSize != 1 && tupleSize != 2) {
  474. PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one or two elements");
  475. return NULL;
  476. } else if (!PyArg_ParseTuple(color, "L|i", &r, &a)) {
  477. return NULL;
  478. }
  479. g = b = r;
  480. } else {
  481. if (tupleSize != 3 && tupleSize != 4) {
  482. PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one, three or four elements");
  483. return NULL;
  484. } else if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) {
  485. return NULL;
  486. }
  487. }
  488. }
  489. ink[0] = (char)CLIP8(r);
  490. ink[1] = (char)CLIP8(g);
  491. ink[2] = (char)CLIP8(b);
  492. ink[3] = (char)CLIP8(a);
  493. }
  494. return ink;
  495. case IMAGING_TYPE_INT32:
  496. /* signed integer */
  497. itmp = r;
  498. memcpy(ink, &itmp, sizeof(itmp));
  499. return ink;
  500. case IMAGING_TYPE_FLOAT32:
  501. /* floating point */
  502. f = PyFloat_AsDouble(color);
  503. if (f == -1.0 && PyErr_Occurred()) {
  504. return NULL;
  505. }
  506. ftmp = f;
  507. memcpy(ink, &ftmp, sizeof(ftmp));
  508. return ink;
  509. case IMAGING_TYPE_SPECIAL:
  510. if (strncmp(im->mode, "I;16", 4) == 0) {
  511. ink[0] = (UINT8)r;
  512. ink[1] = (UINT8)(r >> 8);
  513. ink[2] = ink[3] = 0;
  514. return ink;
  515. } else {
  516. if (rIsInt) {
  517. b = (UINT8)(r >> 16);
  518. g = (UINT8)(r >> 8);
  519. r = (UINT8)r;
  520. } else if (tupleSize != 3) {
  521. PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one or three elements");
  522. return NULL;
  523. } else if (!PyArg_ParseTuple(color, "iiL", &b, &g, &r)) {
  524. return NULL;
  525. }
  526. if (!strcmp(im->mode, "BGR;15")) {
  527. UINT16 v = ((((UINT16)r) << 7) & 0x7c00) +
  528. ((((UINT16)g) << 2) & 0x03e0) +
  529. ((((UINT16)b) >> 3) & 0x001f);
  530. ink[0] = (UINT8)v;
  531. ink[1] = (UINT8)(v >> 8);
  532. ink[2] = ink[3] = 0;
  533. return ink;
  534. } else if (!strcmp(im->mode, "BGR;16")) {
  535. UINT16 v = ((((UINT16)r) << 8) & 0xf800) +
  536. ((((UINT16)g) << 3) & 0x07e0) +
  537. ((((UINT16)b) >> 3) & 0x001f);
  538. ink[0] = (UINT8)v;
  539. ink[1] = (UINT8)(v >> 8);
  540. ink[2] = ink[3] = 0;
  541. return ink;
  542. } else if (!strcmp(im->mode, "BGR;24")) {
  543. ink[0] = (UINT8)b;
  544. ink[1] = (UINT8)g;
  545. ink[2] = (UINT8)r;
  546. ink[3] = 0;
  547. return ink;
  548. }
  549. }
  550. }
  551. PyErr_SetString(PyExc_ValueError, wrong_mode);
  552. return NULL;
  553. }
  554. /* -------------------------------------------------------------------- */
  555. /* FACTORIES */
  556. /* -------------------------------------------------------------------- */
  557. static PyObject *
  558. _fill(PyObject *self, PyObject *args) {
  559. char *mode;
  560. int xsize, ysize;
  561. PyObject *color;
  562. char buffer[4];
  563. Imaging im;
  564. xsize = ysize = 256;
  565. color = NULL;
  566. if (!PyArg_ParseTuple(args, "s|(ii)O", &mode, &xsize, &ysize, &color)) {
  567. return NULL;
  568. }
  569. im = ImagingNewDirty(mode, xsize, ysize);
  570. if (!im) {
  571. return NULL;
  572. }
  573. buffer[0] = buffer[1] = buffer[2] = buffer[3] = 0;
  574. if (color) {
  575. if (!getink(color, im, buffer)) {
  576. ImagingDelete(im);
  577. return NULL;
  578. }
  579. }
  580. (void)ImagingFill(im, buffer);
  581. return PyImagingNew(im);
  582. }
  583. static PyObject *
  584. _new(PyObject *self, PyObject *args) {
  585. char *mode;
  586. int xsize, ysize;
  587. if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) {
  588. return NULL;
  589. }
  590. return PyImagingNew(ImagingNew(mode, xsize, ysize));
  591. }
  592. static PyObject *
  593. _new_block(PyObject *self, PyObject *args) {
  594. char *mode;
  595. int xsize, ysize;
  596. if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) {
  597. return NULL;
  598. }
  599. return PyImagingNew(ImagingNewBlock(mode, xsize, ysize));
  600. }
  601. static PyObject *
  602. _linear_gradient(PyObject *self, PyObject *args) {
  603. char *mode;
  604. if (!PyArg_ParseTuple(args, "s", &mode)) {
  605. return NULL;
  606. }
  607. return PyImagingNew(ImagingFillLinearGradient(mode));
  608. }
  609. static PyObject *
  610. _radial_gradient(PyObject *self, PyObject *args) {
  611. char *mode;
  612. if (!PyArg_ParseTuple(args, "s", &mode)) {
  613. return NULL;
  614. }
  615. return PyImagingNew(ImagingFillRadialGradient(mode));
  616. }
  617. static PyObject *
  618. _alpha_composite(ImagingObject *self, PyObject *args) {
  619. ImagingObject *imagep1;
  620. ImagingObject *imagep2;
  621. if (!PyArg_ParseTuple(
  622. args, "O!O!", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2)) {
  623. return NULL;
  624. }
  625. return PyImagingNew(ImagingAlphaComposite(imagep1->image, imagep2->image));
  626. }
  627. static PyObject *
  628. _blend(ImagingObject *self, PyObject *args) {
  629. ImagingObject *imagep1;
  630. ImagingObject *imagep2;
  631. double alpha;
  632. alpha = 0.5;
  633. if (!PyArg_ParseTuple(
  634. args, "O!O!|d", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2, &alpha)) {
  635. return NULL;
  636. }
  637. return PyImagingNew(ImagingBlend(imagep1->image, imagep2->image, (float)alpha));
  638. }
  639. /* -------------------------------------------------------------------- */
  640. /* METHODS */
  641. /* -------------------------------------------------------------------- */
  642. static INT16 *
  643. _prepare_lut_table(PyObject *table, Py_ssize_t table_size) {
  644. int i;
  645. Py_buffer buffer_info;
  646. INT32 data_type = TYPE_FLOAT32;
  647. float item = 0;
  648. void *table_data = NULL;
  649. int free_table_data = 0;
  650. INT16 *prepared;
  651. /* NOTE: This value should be the same as in ColorLUT.c */
  652. #define PRECISION_BITS (16 - 8 - 2)
  653. const char *wrong_size =
  654. ("The table should have table_channels * "
  655. "size1D * size2D * size3D float items.");
  656. if (PyObject_CheckBuffer(table)) {
  657. if (!PyObject_GetBuffer(table, &buffer_info, PyBUF_CONTIG_RO | PyBUF_FORMAT)) {
  658. if (buffer_info.ndim == 1 && buffer_info.shape[0] == table_size) {
  659. if (strlen(buffer_info.format) == 1) {
  660. switch (buffer_info.format[0]) {
  661. case 'e':
  662. data_type = TYPE_FLOAT16;
  663. table_data = buffer_info.buf;
  664. break;
  665. case 'f':
  666. data_type = TYPE_FLOAT32;
  667. table_data = buffer_info.buf;
  668. break;
  669. case 'd':
  670. data_type = TYPE_DOUBLE;
  671. table_data = buffer_info.buf;
  672. break;
  673. }
  674. }
  675. }
  676. PyBuffer_Release(&buffer_info);
  677. }
  678. }
  679. if (!table_data) {
  680. free_table_data = 1;
  681. table_data = getlist(table, &table_size, wrong_size, TYPE_FLOAT32);
  682. if (!table_data) {
  683. return NULL;
  684. }
  685. }
  686. /* malloc check ok, max is 2 * 4 * 65**3 = 2197000 */
  687. prepared = (INT16 *)malloc(sizeof(INT16) * table_size);
  688. if (!prepared) {
  689. if (free_table_data) {
  690. free(table_data);
  691. }
  692. return (INT16 *)ImagingError_MemoryError();
  693. }
  694. for (i = 0; i < table_size; i++) {
  695. FLOAT16 htmp;
  696. double dtmp;
  697. switch (data_type) {
  698. case TYPE_FLOAT16:
  699. memcpy(&htmp, ((char *)table_data) + i * sizeof(htmp), sizeof(htmp));
  700. item = float16tofloat32(htmp);
  701. break;
  702. case TYPE_FLOAT32:
  703. memcpy(
  704. &item, ((char *)table_data) + i * sizeof(FLOAT32), sizeof(FLOAT32));
  705. break;
  706. case TYPE_DOUBLE:
  707. memcpy(&dtmp, ((char *)table_data) + i * sizeof(dtmp), sizeof(dtmp));
  708. item = (FLOAT32)dtmp;
  709. break;
  710. }
  711. /* Max value for INT16 */
  712. if (item >= (0x7fff - 0.5) / (255 << PRECISION_BITS)) {
  713. prepared[i] = 0x7fff;
  714. continue;
  715. }
  716. /* Min value for INT16 */
  717. if (item <= (-0x8000 + 0.5) / (255 << PRECISION_BITS)) {
  718. prepared[i] = -0x8000;
  719. continue;
  720. }
  721. if (item < 0) {
  722. prepared[i] = item * (255 << PRECISION_BITS) - 0.5;
  723. } else {
  724. prepared[i] = item * (255 << PRECISION_BITS) + 0.5;
  725. }
  726. }
  727. #undef PRECISION_BITS
  728. if (free_table_data) {
  729. free(table_data);
  730. }
  731. return prepared;
  732. }
  733. static PyObject *
  734. _color_lut_3d(ImagingObject *self, PyObject *args) {
  735. char *mode;
  736. int filter;
  737. int table_channels;
  738. int size1D, size2D, size3D;
  739. PyObject *table;
  740. INT16 *prepared_table;
  741. Imaging imOut;
  742. if (!PyArg_ParseTuple(
  743. args,
  744. "siiiiiO:color_lut_3d",
  745. &mode,
  746. &filter,
  747. &table_channels,
  748. &size1D,
  749. &size2D,
  750. &size3D,
  751. &table)) {
  752. return NULL;
  753. }
  754. /* actually, it is trilinear */
  755. if (filter != IMAGING_TRANSFORM_BILINEAR) {
  756. PyErr_SetString(PyExc_ValueError, "Only LINEAR filter is supported.");
  757. return NULL;
  758. }
  759. if (1 > table_channels || table_channels > 4) {
  760. PyErr_SetString(PyExc_ValueError, "table_channels should be from 1 to 4");
  761. return NULL;
  762. }
  763. if (2 > size1D || size1D > 65 || 2 > size2D || size2D > 65 || 2 > size3D ||
  764. size3D > 65) {
  765. PyErr_SetString(
  766. PyExc_ValueError, "Table size in any dimension should be from 2 to 65");
  767. return NULL;
  768. }
  769. prepared_table =
  770. _prepare_lut_table(table, table_channels * size1D * size2D * size3D);
  771. if (!prepared_table) {
  772. return NULL;
  773. }
  774. imOut = ImagingNewDirty(mode, self->image->xsize, self->image->ysize);
  775. if (!imOut) {
  776. free(prepared_table);
  777. return NULL;
  778. }
  779. if (!ImagingColorLUT3D_linear(
  780. imOut,
  781. self->image,
  782. table_channels,
  783. size1D,
  784. size2D,
  785. size3D,
  786. prepared_table)) {
  787. free(prepared_table);
  788. ImagingDelete(imOut);
  789. return NULL;
  790. }
  791. free(prepared_table);
  792. return PyImagingNew(imOut);
  793. }
  794. static PyObject *
  795. _convert(ImagingObject *self, PyObject *args) {
  796. char *mode;
  797. int dither = 0;
  798. ImagingObject *paletteimage = NULL;
  799. if (!PyArg_ParseTuple(args, "s|iO", &mode, &dither, &paletteimage)) {
  800. return NULL;
  801. }
  802. if (paletteimage != NULL) {
  803. if (!PyImaging_Check(paletteimage)) {
  804. PyObject_Print((PyObject *)paletteimage, stderr, 0);
  805. PyErr_SetString(
  806. PyExc_ValueError, "palette argument must be image with mode 'P'");
  807. return NULL;
  808. }
  809. if (paletteimage->image->palette == NULL) {
  810. PyErr_SetString(PyExc_ValueError, "null palette");
  811. return NULL;
  812. }
  813. }
  814. return PyImagingNew(ImagingConvert(
  815. self->image, mode, paletteimage ? paletteimage->image->palette : NULL, dither));
  816. }
  817. static PyObject *
  818. _convert2(ImagingObject *self, PyObject *args) {
  819. ImagingObject *imagep1;
  820. ImagingObject *imagep2;
  821. if (!PyArg_ParseTuple(
  822. args, "O!O!", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2)) {
  823. return NULL;
  824. }
  825. if (!ImagingConvert2(imagep1->image, imagep2->image)) {
  826. return NULL;
  827. }
  828. Py_INCREF(Py_None);
  829. return Py_None;
  830. }
  831. static PyObject *
  832. _convert_matrix(ImagingObject *self, PyObject *args) {
  833. char *mode;
  834. float m[12];
  835. if (!PyArg_ParseTuple(args, "s(ffff)", &mode, m + 0, m + 1, m + 2, m + 3)) {
  836. PyErr_Clear();
  837. if (!PyArg_ParseTuple(
  838. args,
  839. "s(ffffffffffff)",
  840. &mode,
  841. m + 0,
  842. m + 1,
  843. m + 2,
  844. m + 3,
  845. m + 4,
  846. m + 5,
  847. m + 6,
  848. m + 7,
  849. m + 8,
  850. m + 9,
  851. m + 10,
  852. m + 11)) {
  853. return NULL;
  854. }
  855. }
  856. return PyImagingNew(ImagingConvertMatrix(self->image, mode, m));
  857. }
  858. static PyObject *
  859. _convert_transparent(ImagingObject *self, PyObject *args) {
  860. char *mode;
  861. int r, g, b;
  862. if (PyArg_ParseTuple(args, "s(iii)", &mode, &r, &g, &b)) {
  863. return PyImagingNew(ImagingConvertTransparent(self->image, mode, r, g, b));
  864. }
  865. PyErr_Clear();
  866. if (PyArg_ParseTuple(args, "si", &mode, &r)) {
  867. return PyImagingNew(ImagingConvertTransparent(self->image, mode, r, 0, 0));
  868. }
  869. return NULL;
  870. }
  871. static PyObject *
  872. _copy(ImagingObject *self, PyObject *args) {
  873. if (!PyArg_ParseTuple(args, "")) {
  874. return NULL;
  875. }
  876. return PyImagingNew(ImagingCopy(self->image));
  877. }
  878. static PyObject *
  879. _crop(ImagingObject *self, PyObject *args) {
  880. int x0, y0, x1, y1;
  881. if (!PyArg_ParseTuple(args, "(iiii)", &x0, &y0, &x1, &y1)) {
  882. return NULL;
  883. }
  884. return PyImagingNew(ImagingCrop(self->image, x0, y0, x1, y1));
  885. }
  886. static PyObject *
  887. _expand_image(ImagingObject *self, PyObject *args) {
  888. int x, y;
  889. if (!PyArg_ParseTuple(args, "ii", &x, &y)) {
  890. return NULL;
  891. }
  892. return PyImagingNew(ImagingExpand(self->image, x, y));
  893. }
  894. static PyObject *
  895. _filter(ImagingObject *self, PyObject *args) {
  896. PyObject *imOut;
  897. Py_ssize_t kernelsize;
  898. FLOAT32 *kerneldata;
  899. int xsize, ysize, i;
  900. float divisor, offset;
  901. PyObject *kernel = NULL;
  902. if (!PyArg_ParseTuple(
  903. args, "(ii)ffO", &xsize, &ysize, &divisor, &offset, &kernel)) {
  904. return NULL;
  905. }
  906. /* get user-defined kernel */
  907. kerneldata = getlist(kernel, &kernelsize, NULL, TYPE_FLOAT32);
  908. if (!kerneldata) {
  909. return NULL;
  910. }
  911. if (kernelsize != (Py_ssize_t)xsize * (Py_ssize_t)ysize) {
  912. free(kerneldata);
  913. return ImagingError_ValueError("bad kernel size");
  914. }
  915. for (i = 0; i < kernelsize; ++i) {
  916. kerneldata[i] /= divisor;
  917. }
  918. imOut = PyImagingNew(ImagingFilter(self->image, xsize, ysize, kerneldata, offset));
  919. free(kerneldata);
  920. return imOut;
  921. }
  922. #ifdef WITH_UNSHARPMASK
  923. static PyObject *
  924. _gaussian_blur(ImagingObject *self, PyObject *args) {
  925. Imaging imIn;
  926. Imaging imOut;
  927. float xradius, yradius;
  928. int passes = 3;
  929. if (!PyArg_ParseTuple(args, "(ff)|i", &xradius, &yradius, &passes)) {
  930. return NULL;
  931. }
  932. imIn = self->image;
  933. imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
  934. if (!imOut) {
  935. return NULL;
  936. }
  937. if (!ImagingGaussianBlur(imOut, imIn, xradius, yradius, passes)) {
  938. ImagingDelete(imOut);
  939. return NULL;
  940. }
  941. return PyImagingNew(imOut);
  942. }
  943. #endif
  944. static PyObject *
  945. _getpalette(ImagingObject *self, PyObject *args) {
  946. PyObject *palette;
  947. int palettesize;
  948. int bits;
  949. ImagingShuffler pack;
  950. char *mode = "RGB";
  951. char *rawmode = "RGB";
  952. if (!PyArg_ParseTuple(args, "|ss", &mode, &rawmode)) {
  953. return NULL;
  954. }
  955. if (!self->image->palette) {
  956. PyErr_SetString(PyExc_ValueError, no_palette);
  957. return NULL;
  958. }
  959. pack = ImagingFindPacker(mode, rawmode, &bits);
  960. if (!pack) {
  961. PyErr_SetString(PyExc_ValueError, wrong_raw_mode);
  962. return NULL;
  963. }
  964. palettesize = self->image->palette->size;
  965. palette = PyBytes_FromStringAndSize(NULL, palettesize * bits / 8);
  966. if (!palette) {
  967. return NULL;
  968. }
  969. pack(
  970. (UINT8 *)PyBytes_AsString(palette), self->image->palette->palette, palettesize);
  971. return palette;
  972. }
  973. static PyObject *
  974. _getpalettemode(ImagingObject *self) {
  975. if (!self->image->palette) {
  976. PyErr_SetString(PyExc_ValueError, no_palette);
  977. return NULL;
  978. }
  979. return PyUnicode_FromString(self->image->palette->mode);
  980. }
  981. static inline int
  982. _getxy(PyObject *xy, int *x, int *y) {
  983. PyObject *value;
  984. if (!PyTuple_Check(xy) || PyTuple_GET_SIZE(xy) != 2) {
  985. goto badarg;
  986. }
  987. value = PyTuple_GET_ITEM(xy, 0);
  988. if (PyLong_Check(value)) {
  989. *x = PyLong_AS_LONG(value);
  990. } else if (PyFloat_Check(value)) {
  991. *x = (int)PyFloat_AS_DOUBLE(value);
  992. } else {
  993. PyObject *int_value = PyObject_CallMethod(value, "__int__", NULL);
  994. if (int_value != NULL && PyLong_Check(int_value)) {
  995. *x = PyLong_AS_LONG(int_value);
  996. } else {
  997. goto badval;
  998. }
  999. }
  1000. value = PyTuple_GET_ITEM(xy, 1);
  1001. if (PyLong_Check(value)) {
  1002. *y = PyLong_AS_LONG(value);
  1003. } else if (PyFloat_Check(value)) {
  1004. *y = (int)PyFloat_AS_DOUBLE(value);
  1005. } else {
  1006. PyObject *int_value = PyObject_CallMethod(value, "__int__", NULL);
  1007. if (int_value != NULL && PyLong_Check(int_value)) {
  1008. *y = PyLong_AS_LONG(int_value);
  1009. } else {
  1010. goto badval;
  1011. }
  1012. }
  1013. return 0;
  1014. badarg:
  1015. PyErr_SetString(PyExc_TypeError, "argument must be sequence of length 2");
  1016. return -1;
  1017. badval:
  1018. PyErr_SetString(PyExc_TypeError, "an integer is required");
  1019. return -1;
  1020. }
  1021. static PyObject *
  1022. _getpixel(ImagingObject *self, PyObject *args) {
  1023. PyObject *xy;
  1024. int x, y;
  1025. if (PyTuple_GET_SIZE(args) != 1) {
  1026. PyErr_SetString(PyExc_TypeError, "argument 1 must be sequence of length 2");
  1027. return NULL;
  1028. }
  1029. xy = PyTuple_GET_ITEM(args, 0);
  1030. if (_getxy(xy, &x, &y)) {
  1031. return NULL;
  1032. }
  1033. if (self->access == NULL) {
  1034. Py_INCREF(Py_None);
  1035. return Py_None;
  1036. }
  1037. return getpixel(self->image, self->access, x, y);
  1038. }
  1039. union hist_extrema {
  1040. UINT8 u[2];
  1041. INT32 i[2];
  1042. FLOAT32 f[2];
  1043. };
  1044. static union hist_extrema *
  1045. parse_histogram_extremap(
  1046. ImagingObject *self, PyObject *extremap, union hist_extrema *ep) {
  1047. int i0, i1;
  1048. double f0, f1;
  1049. if (extremap) {
  1050. switch (self->image->type) {
  1051. case IMAGING_TYPE_UINT8:
  1052. if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) {
  1053. return NULL;
  1054. }
  1055. ep->u[0] = CLIP8(i0);
  1056. ep->u[1] = CLIP8(i1);
  1057. break;
  1058. case IMAGING_TYPE_INT32:
  1059. if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) {
  1060. return NULL;
  1061. }
  1062. ep->i[0] = i0;
  1063. ep->i[1] = i1;
  1064. break;
  1065. case IMAGING_TYPE_FLOAT32:
  1066. if (!PyArg_ParseTuple(extremap, "dd", &f0, &f1)) {
  1067. return NULL;
  1068. }
  1069. ep->f[0] = (FLOAT32)f0;
  1070. ep->f[1] = (FLOAT32)f1;
  1071. break;
  1072. default:
  1073. return NULL;
  1074. }
  1075. } else {
  1076. return NULL;
  1077. }
  1078. return ep;
  1079. }
  1080. static PyObject *
  1081. _histogram(ImagingObject *self, PyObject *args) {
  1082. ImagingHistogram h;
  1083. PyObject *list;
  1084. int i;
  1085. union hist_extrema extrema;
  1086. union hist_extrema *ep;
  1087. PyObject *extremap = NULL;
  1088. ImagingObject *maskp = NULL;
  1089. if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) {
  1090. return NULL;
  1091. }
  1092. /* Using a var to avoid allocations. */
  1093. ep = parse_histogram_extremap(self, extremap, &extrema);
  1094. h = ImagingGetHistogram(self->image, (maskp) ? maskp->image : NULL, ep);
  1095. if (!h) {
  1096. return NULL;
  1097. }
  1098. /* Build an integer list containing the histogram */
  1099. list = PyList_New(h->bands * 256);
  1100. if (list == NULL) {
  1101. ImagingHistogramDelete(h);
  1102. return NULL;
  1103. }
  1104. for (i = 0; i < h->bands * 256; i++) {
  1105. PyObject *item;
  1106. item = PyLong_FromLong(h->histogram[i]);
  1107. if (item == NULL) {
  1108. Py_DECREF(list);
  1109. list = NULL;
  1110. break;
  1111. }
  1112. PyList_SetItem(list, i, item);
  1113. }
  1114. /* Destroy the histogram structure */
  1115. ImagingHistogramDelete(h);
  1116. return list;
  1117. }
  1118. static PyObject *
  1119. _entropy(ImagingObject *self, PyObject *args) {
  1120. ImagingHistogram h;
  1121. int idx, length;
  1122. long sum;
  1123. double entropy, fsum, p;
  1124. union hist_extrema extrema;
  1125. union hist_extrema *ep;
  1126. PyObject *extremap = NULL;
  1127. ImagingObject *maskp = NULL;
  1128. if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) {
  1129. return NULL;
  1130. }
  1131. /* Using a local var to avoid allocations. */
  1132. ep = parse_histogram_extremap(self, extremap, &extrema);
  1133. h = ImagingGetHistogram(self->image, (maskp) ? maskp->image : NULL, ep);
  1134. if (!h) {
  1135. return NULL;
  1136. }
  1137. /* Calculate the histogram entropy */
  1138. /* First, sum the histogram data */
  1139. length = h->bands * 256;
  1140. sum = 0;
  1141. for (idx = 0; idx < length; idx++) {
  1142. sum += h->histogram[idx];
  1143. }
  1144. /* Next, normalize the histogram data, */
  1145. /* using the histogram sum value */
  1146. fsum = (double)sum;
  1147. entropy = 0.0;
  1148. for (idx = 0; idx < length; idx++) {
  1149. p = (double)h->histogram[idx] / fsum;
  1150. if (p != 0.0) {
  1151. entropy += p * log(p) * M_LOG2E;
  1152. }
  1153. }
  1154. /* Destroy the histogram structure */
  1155. ImagingHistogramDelete(h);
  1156. return PyFloat_FromDouble(-entropy);
  1157. }
  1158. #ifdef WITH_MODEFILTER
  1159. static PyObject *
  1160. _modefilter(ImagingObject *self, PyObject *args) {
  1161. int size;
  1162. if (!PyArg_ParseTuple(args, "i", &size)) {
  1163. return NULL;
  1164. }
  1165. return PyImagingNew(ImagingModeFilter(self->image, size));
  1166. }
  1167. #endif
  1168. static PyObject *
  1169. _offset(ImagingObject *self, PyObject *args) {
  1170. int xoffset, yoffset;
  1171. if (!PyArg_ParseTuple(args, "ii", &xoffset, &yoffset)) {
  1172. return NULL;
  1173. }
  1174. return PyImagingNew(ImagingOffset(self->image, xoffset, yoffset));
  1175. }
  1176. static PyObject *
  1177. _paste(ImagingObject *self, PyObject *args) {
  1178. int status;
  1179. char ink[4];
  1180. PyObject *source;
  1181. int x0, y0, x1, y1;
  1182. ImagingObject *maskp = NULL;
  1183. if (!PyArg_ParseTuple(
  1184. args, "O(iiii)|O!", &source, &x0, &y0, &x1, &y1, &Imaging_Type, &maskp)) {
  1185. return NULL;
  1186. }
  1187. if (PyImaging_Check(source)) {
  1188. status = ImagingPaste(
  1189. self->image,
  1190. PyImaging_AsImaging(source),
  1191. (maskp) ? maskp->image : NULL,
  1192. x0,
  1193. y0,
  1194. x1,
  1195. y1);
  1196. } else {
  1197. if (!getink(source, self->image, ink)) {
  1198. return NULL;
  1199. }
  1200. status = ImagingFill2(
  1201. self->image, ink, (maskp) ? maskp->image : NULL, x0, y0, x1, y1);
  1202. }
  1203. if (status < 0) {
  1204. return NULL;
  1205. }
  1206. Py_INCREF(Py_None);
  1207. return Py_None;
  1208. }
  1209. static PyObject *
  1210. _point(ImagingObject *self, PyObject *args) {
  1211. static const char *wrong_number = "wrong number of lut entries";
  1212. Py_ssize_t n;
  1213. int i, bands;
  1214. Imaging im;
  1215. PyObject *list;
  1216. char *mode;
  1217. if (!PyArg_ParseTuple(args, "Oz", &list, &mode)) {
  1218. return NULL;
  1219. }
  1220. if (mode && !strcmp(mode, "F")) {
  1221. FLOAT32 *data;
  1222. /* map from 8-bit data to floating point */
  1223. n = 256;
  1224. data = getlist(list, &n, wrong_number, TYPE_FLOAT32);
  1225. if (!data) {
  1226. return NULL;
  1227. }
  1228. im = ImagingPoint(self->image, mode, (void *)data);
  1229. free(data);
  1230. } else if (!strcmp(self->image->mode, "I") && mode && !strcmp(mode, "L")) {
  1231. UINT8 *data;
  1232. /* map from 16-bit subset of 32-bit data to 8-bit */
  1233. /* FIXME: support arbitrary number of entries (requires API change) */
  1234. n = 65536;
  1235. data = getlist(list, &n, wrong_number, TYPE_UINT8);
  1236. if (!data) {
  1237. return NULL;
  1238. }
  1239. im = ImagingPoint(self->image, mode, (void *)data);
  1240. free(data);
  1241. } else {
  1242. INT32 *data;
  1243. UINT8 lut[1024];
  1244. if (mode) {
  1245. bands = getbands(mode);
  1246. if (bands < 0) {
  1247. return NULL;
  1248. }
  1249. } else {
  1250. bands = self->image->bands;
  1251. }
  1252. /* map to integer data */
  1253. n = 256 * bands;
  1254. data = getlist(list, &n, wrong_number, TYPE_INT32);
  1255. if (!data) {
  1256. return NULL;
  1257. }
  1258. if (mode && !strcmp(mode, "I")) {
  1259. im = ImagingPoint(self->image, mode, (void *)data);
  1260. } else if (mode && bands > 1) {
  1261. for (i = 0; i < 256; i++) {
  1262. lut[i * 4] = CLIP8(data[i]);
  1263. lut[i * 4 + 1] = CLIP8(data[i + 256]);
  1264. lut[i * 4 + 2] = CLIP8(data[i + 512]);
  1265. if (n > 768) {
  1266. lut[i * 4 + 3] = CLIP8(data[i + 768]);
  1267. }
  1268. }
  1269. im = ImagingPoint(self->image, mode, (void *)lut);
  1270. } else {
  1271. /* map individual bands */
  1272. for (i = 0; i < n; i++) {
  1273. lut[i] = CLIP8(data[i]);
  1274. }
  1275. im = ImagingPoint(self->image, mode, (void *)lut);
  1276. }
  1277. free(data);
  1278. }
  1279. return PyImagingNew(im);
  1280. }
  1281. static PyObject *
  1282. _point_transform(ImagingObject *self, PyObject *args) {
  1283. double scale = 1.0;
  1284. double offset = 0.0;
  1285. if (!PyArg_ParseTuple(args, "|dd", &scale, &offset)) {
  1286. return NULL;
  1287. }
  1288. return PyImagingNew(ImagingPointTransform(self->image, scale, offset));
  1289. }
  1290. static PyObject *
  1291. _putdata(ImagingObject *self, PyObject *args) {
  1292. Imaging image;
  1293. // i & n are # pixels, require py_ssize_t. x can be as large as n. y, just because.
  1294. Py_ssize_t n, i, x, y;
  1295. PyObject *data;
  1296. PyObject *seq = NULL;
  1297. PyObject *op;
  1298. double scale = 1.0;
  1299. double offset = 0.0;
  1300. if (!PyArg_ParseTuple(args, "O|dd", &data, &scale, &offset)) {
  1301. return NULL;
  1302. }
  1303. if (!PySequence_Check(data)) {
  1304. PyErr_SetString(PyExc_TypeError, must_be_sequence);
  1305. return NULL;
  1306. }
  1307. image = self->image;
  1308. n = PyObject_Length(data);
  1309. if (n > (Py_ssize_t)image->xsize * (Py_ssize_t)image->ysize) {
  1310. PyErr_SetString(PyExc_TypeError, "too many data entries");
  1311. return NULL;
  1312. }
  1313. #define set_value_to_item(seq, i) \
  1314. op = PySequence_Fast_GET_ITEM(seq, i); \
  1315. if (PySequence_Check(op)) { \
  1316. PyErr_SetString(PyExc_TypeError, "sequence must be flattened"); \
  1317. return NULL; \
  1318. } else { \
  1319. value = PyFloat_AsDouble(op); \
  1320. }
  1321. if (image->image8) {
  1322. if (PyBytes_Check(data)) {
  1323. unsigned char *p;
  1324. p = (unsigned char *)PyBytes_AS_STRING(data);
  1325. if (scale == 1.0 && offset == 0.0) {
  1326. /* Plain string data */
  1327. for (i = y = 0; i < n; i += image->xsize, y++) {
  1328. x = n - i;
  1329. if (x > (int)image->xsize) {
  1330. x = image->xsize;
  1331. }
  1332. memcpy(image->image8[y], p + i, x);
  1333. }
  1334. } else {
  1335. /* Scaled and clipped string data */
  1336. for (i = x = y = 0; i < n; i++) {
  1337. image->image8[y][x] = CLIP8((int)(p[i] * scale + offset));
  1338. if (++x >= (int)image->xsize) {
  1339. x = 0, y++;
  1340. }
  1341. }
  1342. }
  1343. } else {
  1344. seq = PySequence_Fast(data, must_be_sequence);
  1345. if (!seq) {
  1346. PyErr_SetString(PyExc_TypeError, must_be_sequence);
  1347. return NULL;
  1348. }
  1349. double value;
  1350. if (image->bands == 1) {
  1351. int bigendian = 0;
  1352. if (image->type == IMAGING_TYPE_SPECIAL) {
  1353. // I;16*
  1354. bigendian = strcmp(image->mode, "I;16B") == 0;
  1355. }
  1356. for (i = x = y = 0; i < n; i++) {
  1357. set_value_to_item(seq, i);
  1358. if (scale != 1.0 || offset != 0.0) {
  1359. value = value * scale + offset;
  1360. }
  1361. if (image->type == IMAGING_TYPE_SPECIAL) {
  1362. image->image8[y][x * 2 + (bigendian ? 1 : 0)] = CLIP8((int)value % 256);
  1363. image->image8[y][x * 2 + (bigendian ? 0 : 1)] = CLIP8((int)value >> 8);
  1364. } else {
  1365. image->image8[y][x] = (UINT8)CLIP8(value);
  1366. }
  1367. if (++x >= (int)image->xsize) {
  1368. x = 0, y++;
  1369. }
  1370. }
  1371. } else {
  1372. // BGR;*
  1373. int b;
  1374. for (i = x = y = 0; i < n; i++) {
  1375. char ink[4];
  1376. op = PySequence_Fast_GET_ITEM(seq, i);
  1377. if (!op || !getink(op, image, ink)) {
  1378. Py_DECREF(seq);
  1379. return NULL;
  1380. }
  1381. /* FIXME: what about scale and offset? */
  1382. for (b = 0; b < image->pixelsize; b++) {
  1383. image->image8[y][x * image->pixelsize + b] = ink[b];
  1384. }
  1385. if (++x >= (int)image->xsize) {
  1386. x = 0, y++;
  1387. }
  1388. }
  1389. }
  1390. PyErr_Clear(); /* Avoid weird exceptions */
  1391. }
  1392. } else {
  1393. /* 32-bit images */
  1394. seq = PySequence_Fast(data, must_be_sequence);
  1395. if (!seq) {
  1396. PyErr_SetString(PyExc_TypeError, must_be_sequence);
  1397. return NULL;
  1398. }
  1399. switch (image->type) {
  1400. case IMAGING_TYPE_INT32:
  1401. for (i = x = y = 0; i < n; i++) {
  1402. double value;
  1403. set_value_to_item(seq, i);
  1404. IMAGING_PIXEL_INT32(image, x, y) =
  1405. (INT32)(value * scale + offset);
  1406. if (++x >= (int)image->xsize) {
  1407. x = 0, y++;
  1408. }
  1409. }
  1410. PyErr_Clear(); /* Avoid weird exceptions */
  1411. break;
  1412. case IMAGING_TYPE_FLOAT32:
  1413. for (i = x = y = 0; i < n; i++) {
  1414. double value;
  1415. set_value_to_item(seq, i);
  1416. IMAGING_PIXEL_FLOAT32(image, x, y) =
  1417. (FLOAT32)(value * scale + offset);
  1418. if (++x >= (int)image->xsize) {
  1419. x = 0, y++;
  1420. }
  1421. }
  1422. PyErr_Clear(); /* Avoid weird exceptions */
  1423. break;
  1424. default:
  1425. for (i = x = y = 0; i < n; i++) {
  1426. union {
  1427. char ink[4];
  1428. INT32 inkint;
  1429. } u;
  1430. u.inkint = 0;
  1431. op = PySequence_Fast_GET_ITEM(seq, i);
  1432. if (!op || !getink(op, image, u.ink)) {
  1433. Py_DECREF(seq);
  1434. return NULL;
  1435. }
  1436. /* FIXME: what about scale and offset? */
  1437. image->image32[y][x] = u.inkint;
  1438. if (++x >= (int)image->xsize) {
  1439. x = 0, y++;
  1440. }
  1441. }
  1442. PyErr_Clear(); /* Avoid weird exceptions */
  1443. break;
  1444. }
  1445. }
  1446. Py_XDECREF(seq);
  1447. Py_INCREF(Py_None);
  1448. return Py_None;
  1449. }
  1450. #ifdef WITH_QUANTIZE
  1451. static PyObject *
  1452. _quantize(ImagingObject *self, PyObject *args) {
  1453. int colours = 256;
  1454. int method = 0;
  1455. int kmeans = 0;
  1456. if (!PyArg_ParseTuple(args, "|iii", &colours, &method, &kmeans)) {
  1457. return NULL;
  1458. }
  1459. if (!self->image->xsize || !self->image->ysize) {
  1460. /* no content; return an empty image */
  1461. return PyImagingNew(ImagingNew("P", self->image->xsize, self->image->ysize));
  1462. }
  1463. return PyImagingNew(ImagingQuantize(self->image, colours, method, kmeans));
  1464. }
  1465. #endif
  1466. static PyObject *
  1467. _putpalette(ImagingObject *self, PyObject *args) {
  1468. ImagingShuffler unpack;
  1469. int bits;
  1470. char *rawmode, *palette_mode;
  1471. UINT8 *palette;
  1472. Py_ssize_t palettesize;
  1473. if (!PyArg_ParseTuple(args, "sy#", &rawmode, &palette, &palettesize)) {
  1474. return NULL;
  1475. }
  1476. if (strcmp(self->image->mode, "L") && strcmp(self->image->mode, "LA") &&
  1477. strcmp(self->image->mode, "P") && strcmp(self->image->mode, "PA")) {
  1478. PyErr_SetString(PyExc_ValueError, wrong_mode);
  1479. return NULL;
  1480. }
  1481. palette_mode = strncmp("RGBA", rawmode, 4) == 0 ? "RGBA" : "RGB";
  1482. unpack = ImagingFindUnpacker(palette_mode, rawmode, &bits);
  1483. if (!unpack) {
  1484. PyErr_SetString(PyExc_ValueError, wrong_raw_mode);
  1485. return NULL;
  1486. }
  1487. if (palettesize * 8 / bits > 256) {
  1488. PyErr_SetString(PyExc_ValueError, wrong_palette_size);
  1489. return NULL;
  1490. }
  1491. ImagingPaletteDelete(self->image->palette);
  1492. strcpy(self->image->mode, strlen(self->image->mode) == 2 ? "PA" : "P");
  1493. self->image->palette = ImagingPaletteNew(palette_mode);
  1494. self->image->palette->size = palettesize * 8 / bits;
  1495. unpack(self->image->palette->palette, palette, self->image->palette->size);
  1496. Py_INCREF(Py_None);
  1497. return Py_None;
  1498. }
  1499. static PyObject *
  1500. _putpalettealpha(ImagingObject *self, PyObject *args) {
  1501. int index;
  1502. int alpha = 0;
  1503. if (!PyArg_ParseTuple(args, "i|i", &index, &alpha)) {
  1504. return NULL;
  1505. }
  1506. if (!self->image->palette) {
  1507. PyErr_SetString(PyExc_ValueError, no_palette);
  1508. return NULL;
  1509. }
  1510. if (index < 0 || index >= 256) {
  1511. PyErr_SetString(PyExc_ValueError, outside_palette);
  1512. return NULL;
  1513. }
  1514. strcpy(self->image->palette->mode, "RGBA");
  1515. self->image->palette->palette[index * 4 + 3] = (UINT8)alpha;
  1516. Py_INCREF(Py_None);
  1517. return Py_None;
  1518. }
  1519. static PyObject *
  1520. _putpalettealphas(ImagingObject *self, PyObject *args) {
  1521. int i;
  1522. UINT8 *values;
  1523. Py_ssize_t length;
  1524. if (!PyArg_ParseTuple(args, "y#", &values, &length)) {
  1525. return NULL;
  1526. }
  1527. if (!self->image->palette) {
  1528. PyErr_SetString(PyExc_ValueError, no_palette);
  1529. return NULL;
  1530. }
  1531. if (length > 256) {
  1532. PyErr_SetString(PyExc_ValueError, outside_palette);
  1533. return NULL;
  1534. }
  1535. strcpy(self->image->palette->mode, "RGBA");
  1536. for (i = 0; i < length; i++) {
  1537. self->image->palette->palette[i * 4 + 3] = (UINT8)values[i];
  1538. }
  1539. Py_INCREF(Py_None);
  1540. return Py_None;
  1541. }
  1542. static PyObject *
  1543. _putpixel(ImagingObject *self, PyObject *args) {
  1544. Imaging im;
  1545. char ink[4];
  1546. int x, y;
  1547. PyObject *color;
  1548. if (!PyArg_ParseTuple(args, "(ii)O", &x, &y, &color)) {
  1549. return NULL;
  1550. }
  1551. im = self->image;
  1552. if (x < 0) {
  1553. x = im->xsize + x;
  1554. }
  1555. if (y < 0) {
  1556. y = im->ysize + y;
  1557. }
  1558. if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
  1559. PyErr_SetString(PyExc_IndexError, outside_image);
  1560. return NULL;
  1561. }
  1562. if (!getink(color, im, ink)) {
  1563. return NULL;
  1564. }
  1565. if (self->access) {
  1566. self->access->put_pixel(im, x, y, ink);
  1567. }
  1568. Py_INCREF(Py_None);
  1569. return Py_None;
  1570. }
  1571. #ifdef WITH_RANKFILTER
  1572. static PyObject *
  1573. _rankfilter(ImagingObject *self, PyObject *args) {
  1574. int size, rank;
  1575. if (!PyArg_ParseTuple(args, "ii", &size, &rank)) {
  1576. return NULL;
  1577. }
  1578. return PyImagingNew(ImagingRankFilter(self->image, size, rank));
  1579. }
  1580. #endif
  1581. static PyObject *
  1582. _resize(ImagingObject *self, PyObject *args) {
  1583. Imaging imIn;
  1584. Imaging imOut;
  1585. int xsize, ysize;
  1586. int filter = IMAGING_TRANSFORM_NEAREST;
  1587. float box[4] = {0, 0, 0, 0};
  1588. imIn = self->image;
  1589. box[2] = imIn->xsize;
  1590. box[3] = imIn->ysize;
  1591. if (!PyArg_ParseTuple(
  1592. args,
  1593. "(ii)|i(ffff)",
  1594. &xsize,
  1595. &ysize,
  1596. &filter,
  1597. &box[0],
  1598. &box[1],
  1599. &box[2],
  1600. &box[3])) {
  1601. return NULL;
  1602. }
  1603. if (xsize < 1 || ysize < 1) {
  1604. return ImagingError_ValueError("height and width must be > 0");
  1605. }
  1606. if (box[0] < 0 || box[1] < 0) {
  1607. return ImagingError_ValueError("box offset can't be negative");
  1608. }
  1609. if (box[2] > imIn->xsize || box[3] > imIn->ysize) {
  1610. return ImagingError_ValueError("box can't exceed original image size");
  1611. }
  1612. if (box[2] - box[0] < 0 || box[3] - box[1] < 0) {
  1613. return ImagingError_ValueError("box can't be empty");
  1614. }
  1615. // If box's coordinates are int and box size matches requested size
  1616. if (box[0] - (int)box[0] == 0 && box[2] - box[0] == xsize &&
  1617. box[1] - (int)box[1] == 0 && box[3] - box[1] == ysize) {
  1618. imOut = ImagingCrop(imIn, box[0], box[1], box[2], box[3]);
  1619. } else if (filter == IMAGING_TRANSFORM_NEAREST) {
  1620. double a[8];
  1621. memset(a, 0, sizeof a);
  1622. a[0] = (double)(box[2] - box[0]) / xsize;
  1623. a[4] = (double)(box[3] - box[1]) / ysize;
  1624. a[2] = box[0];
  1625. a[5] = box[1];
  1626. imOut = ImagingNewDirty(imIn->mode, xsize, ysize);
  1627. imOut = ImagingTransform(
  1628. imOut, imIn, IMAGING_TRANSFORM_AFFINE, 0, 0, xsize, ysize, a, filter, 1);
  1629. } else {
  1630. imOut = ImagingResample(imIn, xsize, ysize, filter, box);
  1631. }
  1632. return PyImagingNew(imOut);
  1633. }
  1634. static PyObject *
  1635. _reduce(ImagingObject *self, PyObject *args) {
  1636. Imaging imIn;
  1637. Imaging imOut;
  1638. int xscale, yscale;
  1639. int box[4] = {0, 0, 0, 0};
  1640. imIn = self->image;
  1641. box[2] = imIn->xsize;
  1642. box[3] = imIn->ysize;
  1643. if (!PyArg_ParseTuple(
  1644. args,
  1645. "(ii)|(iiii)",
  1646. &xscale,
  1647. &yscale,
  1648. &box[0],
  1649. &box[1],
  1650. &box[2],
  1651. &box[3])) {
  1652. return NULL;
  1653. }
  1654. if (xscale < 1 || yscale < 1) {
  1655. return ImagingError_ValueError("scale must be > 0");
  1656. }
  1657. if (box[0] < 0 || box[1] < 0) {
  1658. return ImagingError_ValueError("box offset can't be negative");
  1659. }
  1660. if (box[2] > imIn->xsize || box[3] > imIn->ysize) {
  1661. return ImagingError_ValueError("box can't exceed original image size");
  1662. }
  1663. if (box[2] <= box[0] || box[3] <= box[1]) {
  1664. return ImagingError_ValueError("box can't be empty");
  1665. }
  1666. if (xscale == 1 && yscale == 1) {
  1667. imOut = ImagingCrop(imIn, box[0], box[1], box[2], box[3]);
  1668. } else {
  1669. // Change box format: (left, top, width, height)
  1670. box[2] -= box[0];
  1671. box[3] -= box[1];
  1672. imOut = ImagingReduce(imIn, xscale, yscale, box);
  1673. }
  1674. return PyImagingNew(imOut);
  1675. }
  1676. #define IS_RGB(mode) \
  1677. (!strcmp(mode, "RGB") || !strcmp(mode, "RGBA") || !strcmp(mode, "RGBX"))
  1678. static PyObject *
  1679. im_setmode(ImagingObject *self, PyObject *args) {
  1680. /* attempt to modify the mode of an image in place */
  1681. Imaging im;
  1682. char *mode;
  1683. Py_ssize_t modelen;
  1684. if (!PyArg_ParseTuple(args, "s#:setmode", &mode, &modelen)) {
  1685. return NULL;
  1686. }
  1687. im = self->image;
  1688. /* move all logic in here to the libImaging primitive */
  1689. if (!strcmp(im->mode, mode)) {
  1690. ; /* same mode; always succeeds */
  1691. } else if (IS_RGB(im->mode) && IS_RGB(mode)) {
  1692. /* color to color */
  1693. strcpy(im->mode, mode);
  1694. im->bands = modelen;
  1695. if (!strcmp(mode, "RGBA")) {
  1696. (void)ImagingFillBand(im, 3, 255);
  1697. }
  1698. } else {
  1699. /* trying doing an in-place conversion */
  1700. if (!ImagingConvertInPlace(im, mode)) {
  1701. return NULL;
  1702. }
  1703. }
  1704. if (self->access) {
  1705. ImagingAccessDelete(im, self->access);
  1706. }
  1707. self->access = ImagingAccessNew(im);
  1708. Py_INCREF(Py_None);
  1709. return Py_None;
  1710. }
  1711. static PyObject *
  1712. _transform2(ImagingObject *self, PyObject *args) {
  1713. static const char *wrong_number = "wrong number of matrix entries";
  1714. Imaging imOut;
  1715. Py_ssize_t n;
  1716. double *a;
  1717. ImagingObject *imagep;
  1718. int x0, y0, x1, y1;
  1719. int method;
  1720. PyObject *data;
  1721. int filter = IMAGING_TRANSFORM_NEAREST;
  1722. int fill = 1;
  1723. if (!PyArg_ParseTuple(
  1724. args,
  1725. "(iiii)O!iO|ii",
  1726. &x0,
  1727. &y0,
  1728. &x1,
  1729. &y1,
  1730. &Imaging_Type,
  1731. &imagep,
  1732. &method,
  1733. &data,
  1734. &filter,
  1735. &fill)) {
  1736. return NULL;
  1737. }
  1738. switch (method) {
  1739. case IMAGING_TRANSFORM_AFFINE:
  1740. n = 6;
  1741. break;
  1742. case IMAGING_TRANSFORM_PERSPECTIVE:
  1743. n = 8;
  1744. break;
  1745. case IMAGING_TRANSFORM_QUAD:
  1746. n = 8;
  1747. break;
  1748. default:
  1749. n = -1; /* force error */
  1750. }
  1751. a = getlist(data, &n, wrong_number, TYPE_DOUBLE);
  1752. if (!a) {
  1753. return NULL;
  1754. }
  1755. imOut = ImagingTransform(
  1756. self->image, imagep->image, method, x0, y0, x1, y1, a, filter, fill);
  1757. free(a);
  1758. if (!imOut) {
  1759. return NULL;
  1760. }
  1761. Py_INCREF(Py_None);
  1762. return Py_None;
  1763. }
  1764. static PyObject *
  1765. _transpose(ImagingObject *self, PyObject *args) {
  1766. Imaging imIn;
  1767. Imaging imOut;
  1768. int op;
  1769. if (!PyArg_ParseTuple(args, "i", &op)) {
  1770. return NULL;
  1771. }
  1772. imIn = self->image;
  1773. switch (op) {
  1774. case 0: /* flip left right */
  1775. case 1: /* flip top bottom */
  1776. case 3: /* rotate 180 */
  1777. imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
  1778. break;
  1779. case 2: /* rotate 90 */
  1780. case 4: /* rotate 270 */
  1781. case 5: /* transpose */
  1782. case 6: /* transverse */
  1783. imOut = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize);
  1784. break;
  1785. default:
  1786. PyErr_SetString(PyExc_ValueError, "No such transpose operation");
  1787. return NULL;
  1788. }
  1789. if (imOut) {
  1790. switch (op) {
  1791. case 0:
  1792. (void)ImagingFlipLeftRight(imOut, imIn);
  1793. break;
  1794. case 1:
  1795. (void)ImagingFlipTopBottom(imOut, imIn);
  1796. break;
  1797. case 2:
  1798. (void)ImagingRotate90(imOut, imIn);
  1799. break;
  1800. case 3:
  1801. (void)ImagingRotate180(imOut, imIn);
  1802. break;
  1803. case 4:
  1804. (void)ImagingRotate270(imOut, imIn);
  1805. break;
  1806. case 5:
  1807. (void)ImagingTranspose(imOut, imIn);
  1808. break;
  1809. case 6:
  1810. (void)ImagingTransverse(imOut, imIn);
  1811. break;
  1812. }
  1813. }
  1814. return PyImagingNew(imOut);
  1815. }
  1816. #ifdef WITH_UNSHARPMASK
  1817. static PyObject *
  1818. _unsharp_mask(ImagingObject *self, PyObject *args) {
  1819. Imaging imIn;
  1820. Imaging imOut;
  1821. float radius;
  1822. int percent, threshold;
  1823. if (!PyArg_ParseTuple(args, "fii", &radius, &percent, &threshold)) {
  1824. return NULL;
  1825. }
  1826. imIn = self->image;
  1827. imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
  1828. if (!imOut) {
  1829. return NULL;
  1830. }
  1831. if (!ImagingUnsharpMask(imOut, imIn, radius, percent, threshold)) {
  1832. return NULL;
  1833. }
  1834. return PyImagingNew(imOut);
  1835. }
  1836. #endif
  1837. static PyObject *
  1838. _box_blur(ImagingObject *self, PyObject *args) {
  1839. Imaging imIn;
  1840. Imaging imOut;
  1841. float xradius, yradius;
  1842. int n = 1;
  1843. if (!PyArg_ParseTuple(args, "(ff)|i", &xradius, &yradius, &n)) {
  1844. return NULL;
  1845. }
  1846. imIn = self->image;
  1847. imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
  1848. if (!imOut) {
  1849. return NULL;
  1850. }
  1851. if (!ImagingBoxBlur(imOut, imIn, xradius, yradius, n)) {
  1852. ImagingDelete(imOut);
  1853. return NULL;
  1854. }
  1855. return PyImagingNew(imOut);
  1856. }
  1857. /* -------------------------------------------------------------------- */
  1858. static PyObject *
  1859. _isblock(ImagingObject *self) {
  1860. return PyBool_FromLong(self->image->block != NULL);
  1861. }
  1862. static PyObject *
  1863. _getbbox(ImagingObject *self, PyObject *args) {
  1864. int bbox[4];
  1865. int alpha_only = 1;
  1866. if (!PyArg_ParseTuple(args, "|i", &alpha_only)) {
  1867. return NULL;
  1868. }
  1869. if (!ImagingGetBBox(self->image, bbox, alpha_only)) {
  1870. Py_INCREF(Py_None);
  1871. return Py_None;
  1872. }
  1873. return Py_BuildValue("iiii", bbox[0], bbox[1], bbox[2], bbox[3]);
  1874. }
  1875. static PyObject *
  1876. _getcolors(ImagingObject *self, PyObject *args) {
  1877. ImagingColorItem *items;
  1878. int i, colors;
  1879. PyObject *out;
  1880. int maxcolors = 256;
  1881. if (!PyArg_ParseTuple(args, "i:getcolors", &maxcolors)) {
  1882. return NULL;
  1883. }
  1884. items = ImagingGetColors(self->image, maxcolors, &colors);
  1885. if (!items) {
  1886. return NULL;
  1887. }
  1888. if (colors > maxcolors) {
  1889. out = Py_None;
  1890. Py_INCREF(out);
  1891. } else {
  1892. out = PyList_New(colors);
  1893. if (out == NULL) {
  1894. free(items);
  1895. return NULL;
  1896. }
  1897. for (i = 0; i < colors; i++) {
  1898. ImagingColorItem *v = &items[i];
  1899. PyObject *item = Py_BuildValue(
  1900. "iN", v->count, getpixel(self->image, self->access, v->x, v->y));
  1901. PyList_SetItem(out, i, item);
  1902. }
  1903. }
  1904. free(items);
  1905. return out;
  1906. }
  1907. static PyObject *
  1908. _getextrema(ImagingObject *self) {
  1909. union {
  1910. UINT8 u[2];
  1911. INT32 i[2];
  1912. FLOAT32 f[2];
  1913. UINT16 s[2];
  1914. } extrema;
  1915. int status;
  1916. status = ImagingGetExtrema(self->image, &extrema);
  1917. if (status < 0) {
  1918. return NULL;
  1919. }
  1920. if (status) {
  1921. switch (self->image->type) {
  1922. case IMAGING_TYPE_UINT8:
  1923. return Py_BuildValue("BB", extrema.u[0], extrema.u[1]);
  1924. case IMAGING_TYPE_INT32:
  1925. return Py_BuildValue("ii", extrema.i[0], extrema.i[1]);
  1926. case IMAGING_TYPE_FLOAT32:
  1927. return Py_BuildValue("dd", extrema.f[0], extrema.f[1]);
  1928. case IMAGING_TYPE_SPECIAL:
  1929. if (strcmp(self->image->mode, "I;16") == 0) {
  1930. return Py_BuildValue("HH", extrema.s[0], extrema.s[1]);
  1931. }
  1932. }
  1933. }
  1934. Py_INCREF(Py_None);
  1935. return Py_None;
  1936. }
  1937. static PyObject *
  1938. _getprojection(ImagingObject *self) {
  1939. unsigned char *xprofile;
  1940. unsigned char *yprofile;
  1941. PyObject *result;
  1942. /* malloc check ok */
  1943. xprofile = malloc(self->image->xsize);
  1944. yprofile = malloc(self->image->ysize);
  1945. if (xprofile == NULL || yprofile == NULL) {
  1946. free(xprofile);
  1947. free(yprofile);
  1948. return ImagingError_MemoryError();
  1949. }
  1950. ImagingGetProjection(
  1951. self->image, (unsigned char *)xprofile, (unsigned char *)yprofile);
  1952. result = Py_BuildValue(
  1953. "y#y#",
  1954. xprofile,
  1955. (Py_ssize_t)self->image->xsize,
  1956. yprofile,
  1957. (Py_ssize_t)self->image->ysize);
  1958. free(xprofile);
  1959. free(yprofile);
  1960. return result;
  1961. }
  1962. /* -------------------------------------------------------------------- */
  1963. static PyObject *
  1964. _getband(ImagingObject *self, PyObject *args) {
  1965. int band;
  1966. if (!PyArg_ParseTuple(args, "i", &band)) {
  1967. return NULL;
  1968. }
  1969. return PyImagingNew(ImagingGetBand(self->image, band));
  1970. }
  1971. static PyObject *
  1972. _fillband(ImagingObject *self, PyObject *args) {
  1973. int band;
  1974. int color;
  1975. if (!PyArg_ParseTuple(args, "ii", &band, &color)) {
  1976. return NULL;
  1977. }
  1978. if (!ImagingFillBand(self->image, band, color)) {
  1979. return NULL;
  1980. }
  1981. Py_INCREF(Py_None);
  1982. return Py_None;
  1983. }
  1984. static PyObject *
  1985. _putband(ImagingObject *self, PyObject *args) {
  1986. ImagingObject *imagep;
  1987. int band;
  1988. if (!PyArg_ParseTuple(args, "O!i", &Imaging_Type, &imagep, &band)) {
  1989. return NULL;
  1990. }
  1991. if (!ImagingPutBand(self->image, imagep->image, band)) {
  1992. return NULL;
  1993. }
  1994. Py_INCREF(Py_None);
  1995. return Py_None;
  1996. }
  1997. static PyObject *
  1998. _merge(PyObject *self, PyObject *args) {
  1999. char *mode;
  2000. ImagingObject *band0 = NULL;
  2001. ImagingObject *band1 = NULL;
  2002. ImagingObject *band2 = NULL;
  2003. ImagingObject *band3 = NULL;
  2004. Imaging bands[4] = {NULL, NULL, NULL, NULL};
  2005. if (!PyArg_ParseTuple(
  2006. args,
  2007. "sO!|O!O!O!",
  2008. &mode,
  2009. &Imaging_Type,
  2010. &band0,
  2011. &Imaging_Type,
  2012. &band1,
  2013. &Imaging_Type,
  2014. &band2,
  2015. &Imaging_Type,
  2016. &band3)) {
  2017. return NULL;
  2018. }
  2019. if (band0) {
  2020. bands[0] = band0->image;
  2021. }
  2022. if (band1) {
  2023. bands[1] = band1->image;
  2024. }
  2025. if (band2) {
  2026. bands[2] = band2->image;
  2027. }
  2028. if (band3) {
  2029. bands[3] = band3->image;
  2030. }
  2031. return PyImagingNew(ImagingMerge(mode, bands));
  2032. }
  2033. static PyObject *
  2034. _split(ImagingObject *self) {
  2035. int fails = 0;
  2036. Py_ssize_t i;
  2037. PyObject *list;
  2038. PyObject *imaging_object;
  2039. Imaging bands[4] = {NULL, NULL, NULL, NULL};
  2040. if (!ImagingSplit(self->image, bands)) {
  2041. return NULL;
  2042. }
  2043. list = PyTuple_New(self->image->bands);
  2044. for (i = 0; i < self->image->bands; i++) {
  2045. imaging_object = PyImagingNew(bands[i]);
  2046. if (!imaging_object) {
  2047. fails += 1;
  2048. }
  2049. PyTuple_SET_ITEM(list, i, imaging_object);
  2050. }
  2051. if (fails) {
  2052. Py_DECREF(list);
  2053. list = NULL;
  2054. }
  2055. return list;
  2056. }
  2057. /* -------------------------------------------------------------------- */
  2058. #ifdef WITH_IMAGECHOPS
  2059. static PyObject *
  2060. _chop_invert(ImagingObject *self) {
  2061. return PyImagingNew(ImagingNegative(self->image));
  2062. }
  2063. static PyObject *
  2064. _chop_lighter(ImagingObject *self, PyObject *args) {
  2065. ImagingObject *imagep;
  2066. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2067. return NULL;
  2068. }
  2069. return PyImagingNew(ImagingChopLighter(self->image, imagep->image));
  2070. }
  2071. static PyObject *
  2072. _chop_darker(ImagingObject *self, PyObject *args) {
  2073. ImagingObject *imagep;
  2074. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2075. return NULL;
  2076. }
  2077. return PyImagingNew(ImagingChopDarker(self->image, imagep->image));
  2078. }
  2079. static PyObject *
  2080. _chop_difference(ImagingObject *self, PyObject *args) {
  2081. ImagingObject *imagep;
  2082. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2083. return NULL;
  2084. }
  2085. return PyImagingNew(ImagingChopDifference(self->image, imagep->image));
  2086. }
  2087. static PyObject *
  2088. _chop_multiply(ImagingObject *self, PyObject *args) {
  2089. ImagingObject *imagep;
  2090. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2091. return NULL;
  2092. }
  2093. return PyImagingNew(ImagingChopMultiply(self->image, imagep->image));
  2094. }
  2095. static PyObject *
  2096. _chop_screen(ImagingObject *self, PyObject *args) {
  2097. ImagingObject *imagep;
  2098. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2099. return NULL;
  2100. }
  2101. return PyImagingNew(ImagingChopScreen(self->image, imagep->image));
  2102. }
  2103. static PyObject *
  2104. _chop_add(ImagingObject *self, PyObject *args) {
  2105. ImagingObject *imagep;
  2106. float scale;
  2107. int offset;
  2108. scale = 1.0;
  2109. offset = 0;
  2110. if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, &scale, &offset)) {
  2111. return NULL;
  2112. }
  2113. return PyImagingNew(ImagingChopAdd(self->image, imagep->image, scale, offset));
  2114. }
  2115. static PyObject *
  2116. _chop_subtract(ImagingObject *self, PyObject *args) {
  2117. ImagingObject *imagep;
  2118. float scale;
  2119. int offset;
  2120. scale = 1.0;
  2121. offset = 0;
  2122. if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, &scale, &offset)) {
  2123. return NULL;
  2124. }
  2125. return PyImagingNew(ImagingChopSubtract(self->image, imagep->image, scale, offset));
  2126. }
  2127. static PyObject *
  2128. _chop_and(ImagingObject *self, PyObject *args) {
  2129. ImagingObject *imagep;
  2130. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2131. return NULL;
  2132. }
  2133. return PyImagingNew(ImagingChopAnd(self->image, imagep->image));
  2134. }
  2135. static PyObject *
  2136. _chop_or(ImagingObject *self, PyObject *args) {
  2137. ImagingObject *imagep;
  2138. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2139. return NULL;
  2140. }
  2141. return PyImagingNew(ImagingChopOr(self->image, imagep->image));
  2142. }
  2143. static PyObject *
  2144. _chop_xor(ImagingObject *self, PyObject *args) {
  2145. ImagingObject *imagep;
  2146. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2147. return NULL;
  2148. }
  2149. return PyImagingNew(ImagingChopXor(self->image, imagep->image));
  2150. }
  2151. static PyObject *
  2152. _chop_add_modulo(ImagingObject *self, PyObject *args) {
  2153. ImagingObject *imagep;
  2154. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2155. return NULL;
  2156. }
  2157. return PyImagingNew(ImagingChopAddModulo(self->image, imagep->image));
  2158. }
  2159. static PyObject *
  2160. _chop_subtract_modulo(ImagingObject *self, PyObject *args) {
  2161. ImagingObject *imagep;
  2162. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2163. return NULL;
  2164. }
  2165. return PyImagingNew(ImagingChopSubtractModulo(self->image, imagep->image));
  2166. }
  2167. static PyObject *
  2168. _chop_soft_light(ImagingObject *self, PyObject *args) {
  2169. ImagingObject *imagep;
  2170. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2171. return NULL;
  2172. }
  2173. return PyImagingNew(ImagingChopSoftLight(self->image, imagep->image));
  2174. }
  2175. static PyObject *
  2176. _chop_hard_light(ImagingObject *self, PyObject *args) {
  2177. ImagingObject *imagep;
  2178. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2179. return NULL;
  2180. }
  2181. return PyImagingNew(ImagingChopHardLight(self->image, imagep->image));
  2182. }
  2183. static PyObject *
  2184. _chop_overlay(ImagingObject *self, PyObject *args) {
  2185. ImagingObject *imagep;
  2186. if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
  2187. return NULL;
  2188. }
  2189. return PyImagingNew(ImagingOverlay(self->image, imagep->image));
  2190. }
  2191. #endif
  2192. /* -------------------------------------------------------------------- */
  2193. #ifdef WITH_IMAGEDRAW
  2194. static PyObject *
  2195. _font_new(PyObject *self_, PyObject *args) {
  2196. ImagingFontObject *self;
  2197. int i, y0, y1;
  2198. static const char *wrong_length = "descriptor table has wrong size";
  2199. ImagingObject *imagep;
  2200. unsigned char *glyphdata;
  2201. Py_ssize_t glyphdata_length;
  2202. if (!PyArg_ParseTuple(
  2203. args, "O!y#", &Imaging_Type, &imagep, &glyphdata, &glyphdata_length)) {
  2204. return NULL;
  2205. }
  2206. if (glyphdata_length != 256 * 20) {
  2207. PyErr_SetString(PyExc_ValueError, wrong_length);
  2208. return NULL;
  2209. }
  2210. self = PyObject_New(ImagingFontObject, &ImagingFont_Type);
  2211. if (self == NULL) {
  2212. return NULL;
  2213. }
  2214. /* glyph bitmap */
  2215. self->bitmap = imagep->image;
  2216. y0 = y1 = 0;
  2217. /* glyph glyphs */
  2218. for (i = 0; i < 256; i++) {
  2219. self->glyphs[i].dx = S16(B16(glyphdata, 0));
  2220. self->glyphs[i].dy = S16(B16(glyphdata, 2));
  2221. self->glyphs[i].dx0 = S16(B16(glyphdata, 4));
  2222. self->glyphs[i].dy0 = S16(B16(glyphdata, 6));
  2223. self->glyphs[i].dx1 = S16(B16(glyphdata, 8));
  2224. self->glyphs[i].dy1 = S16(B16(glyphdata, 10));
  2225. self->glyphs[i].sx0 = S16(B16(glyphdata, 12));
  2226. self->glyphs[i].sy0 = S16(B16(glyphdata, 14));
  2227. self->glyphs[i].sx1 = S16(B16(glyphdata, 16));
  2228. self->glyphs[i].sy1 = S16(B16(glyphdata, 18));
  2229. // Do not allow glyphs to extend beyond bitmap image
  2230. // Helps prevent DOS by stopping cropped images being larger than the original
  2231. if (self->glyphs[i].sx0 < 0) {
  2232. self->glyphs[i].dx0 -= self->glyphs[i].sx0;
  2233. self->glyphs[i].sx0 = 0;
  2234. }
  2235. if (self->glyphs[i].sy0 < 0) {
  2236. self->glyphs[i].dy0 -= self->glyphs[i].sy0;
  2237. self->glyphs[i].sy0 = 0;
  2238. }
  2239. if (self->glyphs[i].sx1 > self->bitmap->xsize) {
  2240. self->glyphs[i].dx1 -= self->glyphs[i].sx1 - self->bitmap->xsize;
  2241. self->glyphs[i].sx1 = self->bitmap->xsize;
  2242. }
  2243. if (self->glyphs[i].sy1 > self->bitmap->ysize) {
  2244. self->glyphs[i].dy1 -= self->glyphs[i].sy1 - self->bitmap->ysize;
  2245. self->glyphs[i].sy1 = self->bitmap->ysize;
  2246. }
  2247. if (self->glyphs[i].dy0 < y0) {
  2248. y0 = self->glyphs[i].dy0;
  2249. }
  2250. if (self->glyphs[i].dy1 > y1) {
  2251. y1 = self->glyphs[i].dy1;
  2252. }
  2253. glyphdata += 20;
  2254. }
  2255. self->baseline = -y0;
  2256. self->ysize = y1 - y0;
  2257. /* keep a reference to the bitmap object */
  2258. Py_INCREF(imagep);
  2259. self->ref = imagep;
  2260. return (PyObject *)self;
  2261. }
  2262. static void
  2263. _font_dealloc(ImagingFontObject *self) {
  2264. Py_XDECREF(self->ref);
  2265. PyObject_Del(self);
  2266. }
  2267. static inline int
  2268. textwidth(ImagingFontObject *self, const unsigned char *text) {
  2269. int xsize;
  2270. for (xsize = 0; *text; text++) {
  2271. xsize += self->glyphs[*text].dx;
  2272. }
  2273. return xsize;
  2274. }
  2275. void
  2276. _font_text_asBytes(PyObject *encoded_string, unsigned char **text) {
  2277. /* Allocates *text, returns a 'new reference'. Caller is required to free */
  2278. PyObject *bytes = NULL;
  2279. Py_ssize_t len = 0;
  2280. char *buffer;
  2281. *text = NULL;
  2282. if (PyUnicode_CheckExact(encoded_string)) {
  2283. bytes = PyUnicode_AsLatin1String(encoded_string);
  2284. if (!bytes) {
  2285. return;
  2286. }
  2287. PyBytes_AsStringAndSize(bytes, &buffer, &len);
  2288. } else if (PyBytes_Check(encoded_string)) {
  2289. PyBytes_AsStringAndSize(encoded_string, &buffer, &len);
  2290. }
  2291. *text = calloc(len + 1, 1);
  2292. if (*text) {
  2293. memcpy(*text, buffer, len);
  2294. } else {
  2295. ImagingError_MemoryError();
  2296. }
  2297. if (bytes) {
  2298. Py_DECREF(bytes);
  2299. }
  2300. return;
  2301. }
  2302. static PyObject *
  2303. _font_getmask(ImagingFontObject *self, PyObject *args) {
  2304. Imaging im;
  2305. Imaging bitmap = NULL;
  2306. int x, b;
  2307. int i = 0;
  2308. int status;
  2309. Glyph *glyph;
  2310. PyObject *encoded_string;
  2311. unsigned char *text;
  2312. char *mode;
  2313. if (!PyArg_ParseTuple(args, "O|s:getmask", &encoded_string, &mode)) {
  2314. return NULL;
  2315. }
  2316. _font_text_asBytes(encoded_string, &text);
  2317. if (!text) {
  2318. return NULL;
  2319. }
  2320. im = ImagingNew(self->bitmap->mode, textwidth(self, text), self->ysize);
  2321. if (!im) {
  2322. free(text);
  2323. return ImagingError_MemoryError();
  2324. }
  2325. b = 0;
  2326. (void)ImagingFill(im, &b);
  2327. b = self->baseline;
  2328. for (x = 0; text[i]; i++) {
  2329. glyph = &self->glyphs[text[i]];
  2330. if (i == 0 || text[i] != text[i - 1]) {
  2331. ImagingDelete(bitmap);
  2332. bitmap =
  2333. ImagingCrop(self->bitmap, glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1);
  2334. if (!bitmap) {
  2335. goto failed;
  2336. }
  2337. }
  2338. status = ImagingPaste(
  2339. im,
  2340. bitmap,
  2341. NULL,
  2342. glyph->dx0 + x,
  2343. glyph->dy0 + b,
  2344. glyph->dx1 + x,
  2345. glyph->dy1 + b);
  2346. if (status < 0) {
  2347. goto failed;
  2348. }
  2349. x = x + glyph->dx;
  2350. b = b + glyph->dy;
  2351. }
  2352. ImagingDelete(bitmap);
  2353. free(text);
  2354. return PyImagingNew(im);
  2355. failed:
  2356. ImagingDelete(bitmap);
  2357. free(text);
  2358. ImagingDelete(im);
  2359. Py_RETURN_NONE;
  2360. }
  2361. static PyObject *
  2362. _font_getsize(ImagingFontObject *self, PyObject *args) {
  2363. unsigned char *text;
  2364. PyObject *encoded_string;
  2365. PyObject *val;
  2366. if (!PyArg_ParseTuple(args, "O:getsize", &encoded_string)) {
  2367. return NULL;
  2368. }
  2369. _font_text_asBytes(encoded_string, &text);
  2370. if (!text) {
  2371. return NULL;
  2372. }
  2373. val = Py_BuildValue("ii", textwidth(self, text), self->ysize);
  2374. free(text);
  2375. return val;
  2376. }
  2377. static struct PyMethodDef _font_methods[] = {
  2378. {"getmask", (PyCFunction)_font_getmask, METH_VARARGS},
  2379. {"getsize", (PyCFunction)_font_getsize, METH_VARARGS},
  2380. {NULL, NULL} /* sentinel */
  2381. };
  2382. /* -------------------------------------------------------------------- */
  2383. static PyObject *
  2384. _draw_new(PyObject *self_, PyObject *args) {
  2385. ImagingDrawObject *self;
  2386. ImagingObject *imagep;
  2387. int blend = 0;
  2388. if (!PyArg_ParseTuple(args, "O!|i", &Imaging_Type, &imagep, &blend)) {
  2389. return NULL;
  2390. }
  2391. self = PyObject_New(ImagingDrawObject, &ImagingDraw_Type);
  2392. if (self == NULL) {
  2393. return NULL;
  2394. }
  2395. /* keep a reference to the image object */
  2396. Py_INCREF(imagep);
  2397. self->image = imagep;
  2398. self->ink[0] = self->ink[1] = self->ink[2] = self->ink[3] = 0;
  2399. self->blend = blend;
  2400. return (PyObject *)self;
  2401. }
  2402. static void
  2403. _draw_dealloc(ImagingDrawObject *self) {
  2404. Py_XDECREF(self->image);
  2405. PyObject_Del(self);
  2406. }
  2407. extern Py_ssize_t
  2408. PyPath_Flatten(PyObject *data, double **xy);
  2409. static PyObject *
  2410. _draw_ink(ImagingDrawObject *self, PyObject *args) {
  2411. INT32 ink = 0;
  2412. PyObject *color;
  2413. if (!PyArg_ParseTuple(args, "O", &color)) {
  2414. return NULL;
  2415. }
  2416. if (!getink(color, self->image->image, (char *)&ink)) {
  2417. return NULL;
  2418. }
  2419. return PyLong_FromLong((int)ink);
  2420. }
  2421. static PyObject *
  2422. _draw_arc(ImagingDrawObject *self, PyObject *args) {
  2423. double *xy;
  2424. Py_ssize_t n;
  2425. PyObject *data;
  2426. int ink;
  2427. int width = 0;
  2428. float start, end;
  2429. if (!PyArg_ParseTuple(args, "Offi|i", &data, &start, &end, &ink, &width)) {
  2430. return NULL;
  2431. }
  2432. n = PyPath_Flatten(data, &xy);
  2433. if (n < 0) {
  2434. return NULL;
  2435. }
  2436. if (n != 2) {
  2437. PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
  2438. free(xy);
  2439. return NULL;
  2440. }
  2441. if (xy[2] < xy[0]) {
  2442. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_x_coordinate);
  2443. free(xy);
  2444. return NULL;
  2445. }
  2446. if (xy[3] < xy[1]) {
  2447. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_y_coordinate);
  2448. free(xy);
  2449. return NULL;
  2450. }
  2451. n = ImagingDrawArc(
  2452. self->image->image,
  2453. (int)xy[0],
  2454. (int)xy[1],
  2455. (int)xy[2],
  2456. (int)xy[3],
  2457. start,
  2458. end,
  2459. &ink,
  2460. width,
  2461. self->blend);
  2462. free(xy);
  2463. if (n < 0) {
  2464. return NULL;
  2465. }
  2466. Py_INCREF(Py_None);
  2467. return Py_None;
  2468. }
  2469. static PyObject *
  2470. _draw_bitmap(ImagingDrawObject *self, PyObject *args) {
  2471. double *xy;
  2472. Py_ssize_t n;
  2473. PyObject *data;
  2474. ImagingObject *bitmap;
  2475. int ink;
  2476. if (!PyArg_ParseTuple(args, "OO!i", &data, &Imaging_Type, &bitmap, &ink)) {
  2477. return NULL;
  2478. }
  2479. n = PyPath_Flatten(data, &xy);
  2480. if (n < 0) {
  2481. return NULL;
  2482. }
  2483. if (n != 1) {
  2484. PyErr_SetString(
  2485. PyExc_TypeError, "coordinate list must contain exactly 1 coordinate");
  2486. free(xy);
  2487. return NULL;
  2488. }
  2489. n = ImagingDrawBitmap(
  2490. self->image->image, (int)xy[0], (int)xy[1], bitmap->image, &ink, self->blend);
  2491. free(xy);
  2492. if (n < 0) {
  2493. return NULL;
  2494. }
  2495. Py_INCREF(Py_None);
  2496. return Py_None;
  2497. }
  2498. static PyObject *
  2499. _draw_chord(ImagingDrawObject *self, PyObject *args) {
  2500. double *xy;
  2501. Py_ssize_t n;
  2502. PyObject *data;
  2503. int ink, fill;
  2504. int width = 0;
  2505. float start, end;
  2506. if (!PyArg_ParseTuple(args, "Offii|i", &data, &start, &end, &ink, &fill, &width)) {
  2507. return NULL;
  2508. }
  2509. n = PyPath_Flatten(data, &xy);
  2510. if (n < 0) {
  2511. return NULL;
  2512. }
  2513. if (n != 2) {
  2514. PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
  2515. free(xy);
  2516. return NULL;
  2517. }
  2518. if (xy[2] < xy[0]) {
  2519. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_x_coordinate);
  2520. free(xy);
  2521. return NULL;
  2522. }
  2523. if (xy[3] < xy[1]) {
  2524. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_y_coordinate);
  2525. free(xy);
  2526. return NULL;
  2527. }
  2528. n = ImagingDrawChord(
  2529. self->image->image,
  2530. (int)xy[0],
  2531. (int)xy[1],
  2532. (int)xy[2],
  2533. (int)xy[3],
  2534. start,
  2535. end,
  2536. &ink,
  2537. fill,
  2538. width,
  2539. self->blend);
  2540. free(xy);
  2541. if (n < 0) {
  2542. return NULL;
  2543. }
  2544. Py_INCREF(Py_None);
  2545. return Py_None;
  2546. }
  2547. static PyObject *
  2548. _draw_ellipse(ImagingDrawObject *self, PyObject *args) {
  2549. double *xy;
  2550. Py_ssize_t n;
  2551. PyObject *data;
  2552. int ink;
  2553. int fill = 0;
  2554. int width = 0;
  2555. if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) {
  2556. return NULL;
  2557. }
  2558. n = PyPath_Flatten(data, &xy);
  2559. if (n < 0) {
  2560. return NULL;
  2561. }
  2562. if (n != 2) {
  2563. PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
  2564. free(xy);
  2565. return NULL;
  2566. }
  2567. if (xy[2] < xy[0]) {
  2568. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_x_coordinate);
  2569. free(xy);
  2570. return NULL;
  2571. }
  2572. if (xy[3] < xy[1]) {
  2573. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_y_coordinate);
  2574. free(xy);
  2575. return NULL;
  2576. }
  2577. n = ImagingDrawEllipse(
  2578. self->image->image,
  2579. (int)xy[0],
  2580. (int)xy[1],
  2581. (int)xy[2],
  2582. (int)xy[3],
  2583. &ink,
  2584. fill,
  2585. width,
  2586. self->blend);
  2587. free(xy);
  2588. if (n < 0) {
  2589. return NULL;
  2590. }
  2591. Py_INCREF(Py_None);
  2592. return Py_None;
  2593. }
  2594. static PyObject *
  2595. _draw_lines(ImagingDrawObject *self, PyObject *args) {
  2596. double *xy;
  2597. Py_ssize_t i, n;
  2598. PyObject *data;
  2599. int ink;
  2600. int width = 0;
  2601. if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &width)) {
  2602. return NULL;
  2603. }
  2604. n = PyPath_Flatten(data, &xy);
  2605. if (n < 0) {
  2606. return NULL;
  2607. }
  2608. if (width <= 1) {
  2609. double *p = NULL;
  2610. for (i = 0; i < n - 1; i++) {
  2611. p = &xy[i + i];
  2612. if (ImagingDrawLine(
  2613. self->image->image,
  2614. (int)p[0],
  2615. (int)p[1],
  2616. (int)p[2],
  2617. (int)p[3],
  2618. &ink,
  2619. self->blend) < 0) {
  2620. free(xy);
  2621. return NULL;
  2622. }
  2623. }
  2624. if (p) { /* draw last point */
  2625. ImagingDrawPoint(
  2626. self->image->image, (int)p[2], (int)p[3], &ink, self->blend);
  2627. }
  2628. } else {
  2629. for (i = 0; i < n - 1; i++) {
  2630. double *p = &xy[i + i];
  2631. if (ImagingDrawWideLine(
  2632. self->image->image,
  2633. (int)p[0],
  2634. (int)p[1],
  2635. (int)p[2],
  2636. (int)p[3],
  2637. &ink,
  2638. width,
  2639. self->blend) < 0) {
  2640. free(xy);
  2641. return NULL;
  2642. }
  2643. }
  2644. }
  2645. free(xy);
  2646. Py_INCREF(Py_None);
  2647. return Py_None;
  2648. }
  2649. static PyObject *
  2650. _draw_points(ImagingDrawObject *self, PyObject *args) {
  2651. double *xy;
  2652. Py_ssize_t i, n;
  2653. PyObject *data;
  2654. int ink;
  2655. if (!PyArg_ParseTuple(args, "Oi", &data, &ink)) {
  2656. return NULL;
  2657. }
  2658. n = PyPath_Flatten(data, &xy);
  2659. if (n < 0) {
  2660. return NULL;
  2661. }
  2662. for (i = 0; i < n; i++) {
  2663. double *p = &xy[i + i];
  2664. if (ImagingDrawPoint(
  2665. self->image->image, (int)p[0], (int)p[1], &ink, self->blend) < 0) {
  2666. free(xy);
  2667. return NULL;
  2668. }
  2669. }
  2670. free(xy);
  2671. Py_INCREF(Py_None);
  2672. return Py_None;
  2673. }
  2674. #ifdef WITH_ARROW
  2675. /* from outline.c */
  2676. extern ImagingOutline
  2677. PyOutline_AsOutline(PyObject *outline);
  2678. static PyObject *
  2679. _draw_outline(ImagingDrawObject *self, PyObject *args) {
  2680. ImagingOutline outline;
  2681. PyObject *outline_;
  2682. int ink;
  2683. int fill = 0;
  2684. if (!PyArg_ParseTuple(args, "Oi|i", &outline_, &ink, &fill)) {
  2685. return NULL;
  2686. }
  2687. outline = PyOutline_AsOutline(outline_);
  2688. if (!outline) {
  2689. PyErr_SetString(PyExc_TypeError, "expected outline object");
  2690. return NULL;
  2691. }
  2692. if (ImagingDrawOutline(self->image->image, outline, &ink, fill, self->blend) < 0) {
  2693. return NULL;
  2694. }
  2695. Py_INCREF(Py_None);
  2696. return Py_None;
  2697. }
  2698. #endif
  2699. static PyObject *
  2700. _draw_pieslice(ImagingDrawObject *self, PyObject *args) {
  2701. double *xy;
  2702. Py_ssize_t n;
  2703. PyObject *data;
  2704. int ink, fill;
  2705. int width = 0;
  2706. float start, end;
  2707. if (!PyArg_ParseTuple(args, "Offii|i", &data, &start, &end, &ink, &fill, &width)) {
  2708. return NULL;
  2709. }
  2710. n = PyPath_Flatten(data, &xy);
  2711. if (n < 0) {
  2712. return NULL;
  2713. }
  2714. if (n != 2) {
  2715. PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
  2716. free(xy);
  2717. return NULL;
  2718. }
  2719. if (xy[2] < xy[0]) {
  2720. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_x_coordinate);
  2721. free(xy);
  2722. return NULL;
  2723. }
  2724. if (xy[3] < xy[1]) {
  2725. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_y_coordinate);
  2726. free(xy);
  2727. return NULL;
  2728. }
  2729. n = ImagingDrawPieslice(
  2730. self->image->image,
  2731. (int)xy[0],
  2732. (int)xy[1],
  2733. (int)xy[2],
  2734. (int)xy[3],
  2735. start,
  2736. end,
  2737. &ink,
  2738. fill,
  2739. width,
  2740. self->blend);
  2741. free(xy);
  2742. if (n < 0) {
  2743. return NULL;
  2744. }
  2745. Py_INCREF(Py_None);
  2746. return Py_None;
  2747. }
  2748. static PyObject *
  2749. _draw_polygon(ImagingDrawObject *self, PyObject *args) {
  2750. double *xy;
  2751. int *ixy;
  2752. Py_ssize_t n, i;
  2753. PyObject *data;
  2754. int ink;
  2755. int fill = 0;
  2756. int width = 0;
  2757. if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) {
  2758. return NULL;
  2759. }
  2760. n = PyPath_Flatten(data, &xy);
  2761. if (n < 0) {
  2762. return NULL;
  2763. }
  2764. if (n < 2) {
  2765. PyErr_SetString(
  2766. PyExc_TypeError, "coordinate list must contain at least 2 coordinates");
  2767. free(xy);
  2768. return NULL;
  2769. }
  2770. /* Copy list of vertices to array */
  2771. ixy = (int *)calloc(n, 2 * sizeof(int));
  2772. if (ixy == NULL) {
  2773. free(xy);
  2774. return ImagingError_MemoryError();
  2775. }
  2776. for (i = 0; i < n; i++) {
  2777. ixy[i + i] = (int)xy[i + i];
  2778. ixy[i + i + 1] = (int)xy[i + i + 1];
  2779. }
  2780. free(xy);
  2781. if (ImagingDrawPolygon(self->image->image, n, ixy, &ink, fill, width, self->blend) < 0) {
  2782. free(ixy);
  2783. return NULL;
  2784. }
  2785. free(ixy);
  2786. Py_INCREF(Py_None);
  2787. return Py_None;
  2788. }
  2789. static PyObject *
  2790. _draw_rectangle(ImagingDrawObject *self, PyObject *args) {
  2791. double *xy;
  2792. Py_ssize_t n;
  2793. PyObject *data;
  2794. int ink;
  2795. int fill = 0;
  2796. int width = 0;
  2797. if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) {
  2798. return NULL;
  2799. }
  2800. n = PyPath_Flatten(data, &xy);
  2801. if (n < 0) {
  2802. return NULL;
  2803. }
  2804. if (n != 2) {
  2805. PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
  2806. free(xy);
  2807. return NULL;
  2808. }
  2809. if (xy[2] < xy[0]) {
  2810. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_x_coordinate);
  2811. free(xy);
  2812. return NULL;
  2813. }
  2814. if (xy[3] < xy[1]) {
  2815. PyErr_SetString(PyExc_ValueError, incorrectly_ordered_y_coordinate);
  2816. free(xy);
  2817. return NULL;
  2818. }
  2819. n = ImagingDrawRectangle(
  2820. self->image->image,
  2821. (int)xy[0],
  2822. (int)xy[1],
  2823. (int)xy[2],
  2824. (int)xy[3],
  2825. &ink,
  2826. fill,
  2827. width,
  2828. self->blend);
  2829. free(xy);
  2830. if (n < 0) {
  2831. return NULL;
  2832. }
  2833. Py_INCREF(Py_None);
  2834. return Py_None;
  2835. }
  2836. static struct PyMethodDef _draw_methods[] = {
  2837. #ifdef WITH_IMAGEDRAW
  2838. /* Graphics (ImageDraw) */
  2839. {"draw_lines", (PyCFunction)_draw_lines, METH_VARARGS},
  2840. #ifdef WITH_ARROW
  2841. {"draw_outline", (PyCFunction)_draw_outline, METH_VARARGS},
  2842. #endif
  2843. {"draw_polygon", (PyCFunction)_draw_polygon, METH_VARARGS},
  2844. {"draw_rectangle", (PyCFunction)_draw_rectangle, METH_VARARGS},
  2845. {"draw_points", (PyCFunction)_draw_points, METH_VARARGS},
  2846. {"draw_arc", (PyCFunction)_draw_arc, METH_VARARGS},
  2847. {"draw_bitmap", (PyCFunction)_draw_bitmap, METH_VARARGS},
  2848. {"draw_chord", (PyCFunction)_draw_chord, METH_VARARGS},
  2849. {"draw_ellipse", (PyCFunction)_draw_ellipse, METH_VARARGS},
  2850. {"draw_pieslice", (PyCFunction)_draw_pieslice, METH_VARARGS},
  2851. {"draw_ink", (PyCFunction)_draw_ink, METH_VARARGS},
  2852. #endif
  2853. {NULL, NULL} /* sentinel */
  2854. };
  2855. #endif
  2856. static PyObject *
  2857. pixel_access_new(ImagingObject *imagep, PyObject *args) {
  2858. PixelAccessObject *self;
  2859. int readonly = 0;
  2860. if (!PyArg_ParseTuple(args, "|i", &readonly)) {
  2861. return NULL;
  2862. }
  2863. self = PyObject_New(PixelAccessObject, &PixelAccess_Type);
  2864. if (self == NULL) {
  2865. return NULL;
  2866. }
  2867. /* keep a reference to the image object */
  2868. Py_INCREF(imagep);
  2869. self->image = imagep;
  2870. self->readonly = readonly;
  2871. return (PyObject *)self;
  2872. }
  2873. static void
  2874. pixel_access_dealloc(PixelAccessObject *self) {
  2875. Py_XDECREF(self->image);
  2876. PyObject_Del(self);
  2877. }
  2878. static PyObject *
  2879. pixel_access_getitem(PixelAccessObject *self, PyObject *xy) {
  2880. int x, y;
  2881. if (_getxy(xy, &x, &y)) {
  2882. return NULL;
  2883. }
  2884. return getpixel(self->image->image, self->image->access, x, y);
  2885. }
  2886. static int
  2887. pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color) {
  2888. Imaging im = self->image->image;
  2889. char ink[4];
  2890. int x, y;
  2891. if (self->readonly) {
  2892. (void)ImagingError_ValueError(readonly);
  2893. return -1;
  2894. }
  2895. if (_getxy(xy, &x, &y)) {
  2896. return -1;
  2897. }
  2898. if (x < 0) {
  2899. x = im->xsize + x;
  2900. }
  2901. if (y < 0) {
  2902. y = im->ysize + y;
  2903. }
  2904. if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
  2905. PyErr_SetString(PyExc_IndexError, outside_image);
  2906. return -1;
  2907. }
  2908. if (!color) { /* FIXME: raise exception? */
  2909. return 0;
  2910. }
  2911. if (!getink(color, im, ink)) {
  2912. return -1;
  2913. }
  2914. self->image->access->put_pixel(im, x, y, ink);
  2915. return 0;
  2916. }
  2917. /* -------------------------------------------------------------------- */
  2918. /* EFFECTS (experimental) */
  2919. /* -------------------------------------------------------------------- */
  2920. #ifdef WITH_EFFECTS
  2921. static PyObject *
  2922. _effect_mandelbrot(ImagingObject *self, PyObject *args) {
  2923. int xsize = 512;
  2924. int ysize = 512;
  2925. double extent[4];
  2926. int quality = 100;
  2927. extent[0] = -3;
  2928. extent[1] = -2.5;
  2929. extent[2] = 2;
  2930. extent[3] = 2.5;
  2931. if (!PyArg_ParseTuple(
  2932. args,
  2933. "|(ii)(dddd)i",
  2934. &xsize,
  2935. &ysize,
  2936. &extent[0],
  2937. &extent[1],
  2938. &extent[2],
  2939. &extent[3],
  2940. &quality)) {
  2941. return NULL;
  2942. }
  2943. return PyImagingNew(ImagingEffectMandelbrot(xsize, ysize, extent, quality));
  2944. }
  2945. static PyObject *
  2946. _effect_noise(ImagingObject *self, PyObject *args) {
  2947. int xsize, ysize;
  2948. float sigma = 128;
  2949. if (!PyArg_ParseTuple(args, "(ii)|f", &xsize, &ysize, &sigma)) {
  2950. return NULL;
  2951. }
  2952. return PyImagingNew(ImagingEffectNoise(xsize, ysize, sigma));
  2953. }
  2954. static PyObject *
  2955. _effect_spread(ImagingObject *self, PyObject *args) {
  2956. int dist;
  2957. if (!PyArg_ParseTuple(args, "i", &dist)) {
  2958. return NULL;
  2959. }
  2960. return PyImagingNew(ImagingEffectSpread(self->image, dist));
  2961. }
  2962. #endif
  2963. /* -------------------------------------------------------------------- */
  2964. /* UTILITIES */
  2965. /* -------------------------------------------------------------------- */
  2966. static PyObject *
  2967. _getcodecstatus(PyObject *self, PyObject *args) {
  2968. int status;
  2969. char *msg;
  2970. if (!PyArg_ParseTuple(args, "i", &status)) {
  2971. return NULL;
  2972. }
  2973. switch (status) {
  2974. case IMAGING_CODEC_OVERRUN:
  2975. msg = "buffer overrun";
  2976. break;
  2977. case IMAGING_CODEC_BROKEN:
  2978. msg = "broken data stream";
  2979. break;
  2980. case IMAGING_CODEC_UNKNOWN:
  2981. msg = "unrecognized data stream contents";
  2982. break;
  2983. case IMAGING_CODEC_CONFIG:
  2984. msg = "codec configuration error";
  2985. break;
  2986. case IMAGING_CODEC_MEMORY:
  2987. msg = "out of memory";
  2988. break;
  2989. default:
  2990. Py_RETURN_NONE;
  2991. }
  2992. return PyUnicode_FromString(msg);
  2993. }
  2994. /* -------------------------------------------------------------------- */
  2995. /* DEBUGGING HELPERS */
  2996. /* -------------------------------------------------------------------- */
  2997. static PyObject *
  2998. _save_ppm(ImagingObject *self, PyObject *args) {
  2999. char *filename;
  3000. if (!PyArg_ParseTuple(args, "s", &filename)) {
  3001. return NULL;
  3002. }
  3003. if (!ImagingSavePPM(self->image, filename)) {
  3004. return NULL;
  3005. }
  3006. Py_INCREF(Py_None);
  3007. return Py_None;
  3008. }
  3009. /* -------------------------------------------------------------------- */
  3010. /* methods */
  3011. static struct PyMethodDef methods[] = {
  3012. /* Put commonly used methods first */
  3013. {"getpixel", (PyCFunction)_getpixel, METH_VARARGS},
  3014. {"putpixel", (PyCFunction)_putpixel, METH_VARARGS},
  3015. {"pixel_access", (PyCFunction)pixel_access_new, METH_VARARGS},
  3016. /* Standard processing methods (Image) */
  3017. {"color_lut_3d", (PyCFunction)_color_lut_3d, METH_VARARGS},
  3018. {"convert", (PyCFunction)_convert, METH_VARARGS},
  3019. {"convert2", (PyCFunction)_convert2, METH_VARARGS},
  3020. {"convert_matrix", (PyCFunction)_convert_matrix, METH_VARARGS},
  3021. {"convert_transparent", (PyCFunction)_convert_transparent, METH_VARARGS},
  3022. {"copy", (PyCFunction)_copy, METH_VARARGS},
  3023. {"crop", (PyCFunction)_crop, METH_VARARGS},
  3024. {"expand", (PyCFunction)_expand_image, METH_VARARGS},
  3025. {"filter", (PyCFunction)_filter, METH_VARARGS},
  3026. {"histogram", (PyCFunction)_histogram, METH_VARARGS},
  3027. {"entropy", (PyCFunction)_entropy, METH_VARARGS},
  3028. #ifdef WITH_MODEFILTER
  3029. {"modefilter", (PyCFunction)_modefilter, METH_VARARGS},
  3030. #endif
  3031. {"offset", (PyCFunction)_offset, METH_VARARGS},
  3032. {"paste", (PyCFunction)_paste, METH_VARARGS},
  3033. {"point", (PyCFunction)_point, METH_VARARGS},
  3034. {"point_transform", (PyCFunction)_point_transform, METH_VARARGS},
  3035. {"putdata", (PyCFunction)_putdata, METH_VARARGS},
  3036. #ifdef WITH_QUANTIZE
  3037. {"quantize", (PyCFunction)_quantize, METH_VARARGS},
  3038. #endif
  3039. #ifdef WITH_RANKFILTER
  3040. {"rankfilter", (PyCFunction)_rankfilter, METH_VARARGS},
  3041. #endif
  3042. {"resize", (PyCFunction)_resize, METH_VARARGS},
  3043. {"reduce", (PyCFunction)_reduce, METH_VARARGS},
  3044. {"transpose", (PyCFunction)_transpose, METH_VARARGS},
  3045. {"transform2", (PyCFunction)_transform2, METH_VARARGS},
  3046. {"isblock", (PyCFunction)_isblock, METH_NOARGS},
  3047. {"getbbox", (PyCFunction)_getbbox, METH_VARARGS},
  3048. {"getcolors", (PyCFunction)_getcolors, METH_VARARGS},
  3049. {"getextrema", (PyCFunction)_getextrema, METH_NOARGS},
  3050. {"getprojection", (PyCFunction)_getprojection, METH_NOARGS},
  3051. {"getband", (PyCFunction)_getband, METH_VARARGS},
  3052. {"putband", (PyCFunction)_putband, METH_VARARGS},
  3053. {"split", (PyCFunction)_split, METH_NOARGS},
  3054. {"fillband", (PyCFunction)_fillband, METH_VARARGS},
  3055. {"setmode", (PyCFunction)im_setmode, METH_VARARGS},
  3056. {"getpalette", (PyCFunction)_getpalette, METH_VARARGS},
  3057. {"getpalettemode", (PyCFunction)_getpalettemode, METH_NOARGS},
  3058. {"putpalette", (PyCFunction)_putpalette, METH_VARARGS},
  3059. {"putpalettealpha", (PyCFunction)_putpalettealpha, METH_VARARGS},
  3060. {"putpalettealphas", (PyCFunction)_putpalettealphas, METH_VARARGS},
  3061. #ifdef WITH_IMAGECHOPS
  3062. /* Channel operations (ImageChops) */
  3063. {"chop_invert", (PyCFunction)_chop_invert, METH_NOARGS},
  3064. {"chop_lighter", (PyCFunction)_chop_lighter, METH_VARARGS},
  3065. {"chop_darker", (PyCFunction)_chop_darker, METH_VARARGS},
  3066. {"chop_difference", (PyCFunction)_chop_difference, METH_VARARGS},
  3067. {"chop_multiply", (PyCFunction)_chop_multiply, METH_VARARGS},
  3068. {"chop_screen", (PyCFunction)_chop_screen, METH_VARARGS},
  3069. {"chop_add", (PyCFunction)_chop_add, METH_VARARGS},
  3070. {"chop_subtract", (PyCFunction)_chop_subtract, METH_VARARGS},
  3071. {"chop_add_modulo", (PyCFunction)_chop_add_modulo, METH_VARARGS},
  3072. {"chop_subtract_modulo", (PyCFunction)_chop_subtract_modulo, METH_VARARGS},
  3073. {"chop_and", (PyCFunction)_chop_and, METH_VARARGS},
  3074. {"chop_or", (PyCFunction)_chop_or, METH_VARARGS},
  3075. {"chop_xor", (PyCFunction)_chop_xor, METH_VARARGS},
  3076. {"chop_soft_light", (PyCFunction)_chop_soft_light, METH_VARARGS},
  3077. {"chop_hard_light", (PyCFunction)_chop_hard_light, METH_VARARGS},
  3078. {"chop_overlay", (PyCFunction)_chop_overlay, METH_VARARGS},
  3079. #endif
  3080. #ifdef WITH_UNSHARPMASK
  3081. /* Kevin Cazabon's unsharpmask extension */
  3082. {"gaussian_blur", (PyCFunction)_gaussian_blur, METH_VARARGS},
  3083. {"unsharp_mask", (PyCFunction)_unsharp_mask, METH_VARARGS},
  3084. #endif
  3085. {"box_blur", (PyCFunction)_box_blur, METH_VARARGS},
  3086. #ifdef WITH_EFFECTS
  3087. /* Special effects */
  3088. {"effect_spread", (PyCFunction)_effect_spread, METH_VARARGS},
  3089. #endif
  3090. /* Misc. */
  3091. {"new_block", (PyCFunction)_new_block, METH_VARARGS},
  3092. {"save_ppm", (PyCFunction)_save_ppm, METH_VARARGS},
  3093. {NULL, NULL} /* sentinel */
  3094. };
  3095. /* attributes */
  3096. static PyObject *
  3097. _getattr_mode(ImagingObject *self, void *closure) {
  3098. return PyUnicode_FromString(self->image->mode);
  3099. }
  3100. static PyObject *
  3101. _getattr_size(ImagingObject *self, void *closure) {
  3102. return Py_BuildValue("ii", self->image->xsize, self->image->ysize);
  3103. }
  3104. static PyObject *
  3105. _getattr_bands(ImagingObject *self, void *closure) {
  3106. return PyLong_FromLong(self->image->bands);
  3107. }
  3108. static PyObject *
  3109. _getattr_id(ImagingObject *self, void *closure) {
  3110. return PyLong_FromSsize_t((Py_ssize_t)self->image);
  3111. }
  3112. static PyObject *
  3113. _getattr_ptr(ImagingObject *self, void *closure) {
  3114. return PyCapsule_New(self->image, IMAGING_MAGIC, NULL);
  3115. }
  3116. static PyObject *
  3117. _getattr_unsafe_ptrs(ImagingObject *self, void *closure) {
  3118. return Py_BuildValue(
  3119. "(sn)(sn)(sn)",
  3120. "image8",
  3121. self->image->image8,
  3122. "image32",
  3123. self->image->image32,
  3124. "image",
  3125. self->image->image);
  3126. };
  3127. static struct PyGetSetDef getsetters[] = {
  3128. {"mode", (getter)_getattr_mode},
  3129. {"size", (getter)_getattr_size},
  3130. {"bands", (getter)_getattr_bands},
  3131. {"id", (getter)_getattr_id},
  3132. {"ptr", (getter)_getattr_ptr},
  3133. {"unsafe_ptrs", (getter)_getattr_unsafe_ptrs},
  3134. {NULL}};
  3135. /* basic sequence semantics */
  3136. static Py_ssize_t
  3137. image_length(ImagingObject *self) {
  3138. Imaging im = self->image;
  3139. return (Py_ssize_t)im->xsize * im->ysize;
  3140. }
  3141. static PyObject *
  3142. image_item(ImagingObject *self, Py_ssize_t i) {
  3143. int x, y;
  3144. Imaging im = self->image;
  3145. if (im->xsize > 0) {
  3146. x = i % im->xsize;
  3147. y = i / im->xsize;
  3148. } else {
  3149. x = y = 0; /* leave it to getpixel to raise an exception */
  3150. }
  3151. return getpixel(im, self->access, x, y);
  3152. }
  3153. static PySequenceMethods image_as_sequence = {
  3154. (lenfunc)image_length, /*sq_length*/
  3155. (binaryfunc)NULL, /*sq_concat*/
  3156. (ssizeargfunc)NULL, /*sq_repeat*/
  3157. (ssizeargfunc)image_item, /*sq_item*/
  3158. (ssizessizeargfunc)NULL, /*sq_slice*/
  3159. (ssizeobjargproc)NULL, /*sq_ass_item*/
  3160. (ssizessizeobjargproc)NULL, /*sq_ass_slice*/
  3161. };
  3162. /* type description */
  3163. static PyTypeObject Imaging_Type = {
  3164. PyVarObject_HEAD_INIT(NULL, 0) "ImagingCore", /*tp_name*/
  3165. sizeof(ImagingObject), /*tp_basicsize*/
  3166. 0, /*tp_itemsize*/
  3167. /* methods */
  3168. (destructor)_dealloc, /*tp_dealloc*/
  3169. 0, /*tp_vectorcall_offset*/
  3170. 0, /*tp_getattr*/
  3171. 0, /*tp_setattr*/
  3172. 0, /*tp_as_async*/
  3173. 0, /*tp_repr*/
  3174. 0, /*tp_as_number*/
  3175. &image_as_sequence, /*tp_as_sequence*/
  3176. 0, /*tp_as_mapping*/
  3177. 0, /*tp_hash*/
  3178. 0, /*tp_call*/
  3179. 0, /*tp_str*/
  3180. 0, /*tp_getattro*/
  3181. 0, /*tp_setattro*/
  3182. 0, /*tp_as_buffer*/
  3183. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  3184. 0, /*tp_doc*/
  3185. 0, /*tp_traverse*/
  3186. 0, /*tp_clear*/
  3187. 0, /*tp_richcompare*/
  3188. 0, /*tp_weaklistoffset*/
  3189. 0, /*tp_iter*/
  3190. 0, /*tp_iternext*/
  3191. methods, /*tp_methods*/
  3192. 0, /*tp_members*/
  3193. getsetters, /*tp_getset*/
  3194. };
  3195. #ifdef WITH_IMAGEDRAW
  3196. static PyTypeObject ImagingFont_Type = {
  3197. PyVarObject_HEAD_INIT(NULL, 0) "ImagingFont", /*tp_name*/
  3198. sizeof(ImagingFontObject), /*tp_basicsize*/
  3199. 0, /*tp_itemsize*/
  3200. /* methods */
  3201. (destructor)_font_dealloc, /*tp_dealloc*/
  3202. 0, /*tp_vectorcall_offset*/
  3203. 0, /*tp_getattr*/
  3204. 0, /*tp_setattr*/
  3205. 0, /*tp_as_async*/
  3206. 0, /*tp_repr*/
  3207. 0, /*tp_as_number*/
  3208. 0, /*tp_as_sequence*/
  3209. 0, /*tp_as_mapping*/
  3210. 0, /*tp_hash*/
  3211. 0, /*tp_call*/
  3212. 0, /*tp_str*/
  3213. 0, /*tp_getattro*/
  3214. 0, /*tp_setattro*/
  3215. 0, /*tp_as_buffer*/
  3216. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  3217. 0, /*tp_doc*/
  3218. 0, /*tp_traverse*/
  3219. 0, /*tp_clear*/
  3220. 0, /*tp_richcompare*/
  3221. 0, /*tp_weaklistoffset*/
  3222. 0, /*tp_iter*/
  3223. 0, /*tp_iternext*/
  3224. _font_methods, /*tp_methods*/
  3225. 0, /*tp_members*/
  3226. 0, /*tp_getset*/
  3227. };
  3228. static PyTypeObject ImagingDraw_Type = {
  3229. PyVarObject_HEAD_INIT(NULL, 0) "ImagingDraw", /*tp_name*/
  3230. sizeof(ImagingDrawObject), /*tp_basicsize*/
  3231. 0, /*tp_itemsize*/
  3232. /* methods */
  3233. (destructor)_draw_dealloc, /*tp_dealloc*/
  3234. 0, /*tp_vectorcall_offset*/
  3235. 0, /*tp_getattr*/
  3236. 0, /*tp_setattr*/
  3237. 0, /*tp_as_async*/
  3238. 0, /*tp_repr*/
  3239. 0, /*tp_as_number*/
  3240. 0, /*tp_as_sequence*/
  3241. 0, /*tp_as_mapping*/
  3242. 0, /*tp_hash*/
  3243. 0, /*tp_call*/
  3244. 0, /*tp_str*/
  3245. 0, /*tp_getattro*/
  3246. 0, /*tp_setattro*/
  3247. 0, /*tp_as_buffer*/
  3248. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  3249. 0, /*tp_doc*/
  3250. 0, /*tp_traverse*/
  3251. 0, /*tp_clear*/
  3252. 0, /*tp_richcompare*/
  3253. 0, /*tp_weaklistoffset*/
  3254. 0, /*tp_iter*/
  3255. 0, /*tp_iternext*/
  3256. _draw_methods, /*tp_methods*/
  3257. 0, /*tp_members*/
  3258. 0, /*tp_getset*/
  3259. };
  3260. #endif
  3261. static PyMappingMethods pixel_access_as_mapping = {
  3262. (lenfunc)NULL, /*mp_length*/
  3263. (binaryfunc)pixel_access_getitem, /*mp_subscript*/
  3264. (objobjargproc)pixel_access_setitem, /*mp_ass_subscript*/
  3265. };
  3266. /* type description */
  3267. static PyTypeObject PixelAccess_Type = {
  3268. PyVarObject_HEAD_INIT(NULL, 0) "PixelAccess", /*tp_name*/
  3269. sizeof(PixelAccessObject), /*tp_basicsize*/
  3270. 0, /*tp_itemsize*/
  3271. /* methods */
  3272. (destructor)pixel_access_dealloc, /*tp_dealloc*/
  3273. 0, /*tp_vectorcall_offset*/
  3274. 0, /*tp_getattr*/
  3275. 0, /*tp_setattr*/
  3276. 0, /*tp_as_async*/
  3277. 0, /*tp_repr*/
  3278. 0, /*tp_as_number*/
  3279. 0, /*tp_as_sequence*/
  3280. &pixel_access_as_mapping, /*tp_as_mapping*/
  3281. 0 /*tp_hash*/
  3282. };
  3283. /* -------------------------------------------------------------------- */
  3284. static PyObject *
  3285. _get_stats(PyObject *self, PyObject *args) {
  3286. PyObject *d;
  3287. PyObject *v;
  3288. ImagingMemoryArena arena = &ImagingDefaultArena;
  3289. if (!PyArg_ParseTuple(args, ":get_stats")) {
  3290. return NULL;
  3291. }
  3292. d = PyDict_New();
  3293. if (!d) {
  3294. return NULL;
  3295. }
  3296. v = PyLong_FromLong(arena->stats_new_count);
  3297. PyDict_SetItemString(d, "new_count", v ? v : Py_None);
  3298. Py_XDECREF(v);
  3299. v = PyLong_FromLong(arena->stats_allocated_blocks);
  3300. PyDict_SetItemString(d, "allocated_blocks", v ? v : Py_None);
  3301. Py_XDECREF(v);
  3302. v = PyLong_FromLong(arena->stats_reused_blocks);
  3303. PyDict_SetItemString(d, "reused_blocks", v ? v : Py_None);
  3304. Py_XDECREF(v);
  3305. v = PyLong_FromLong(arena->stats_reallocated_blocks);
  3306. PyDict_SetItemString(d, "reallocated_blocks", v ? v : Py_None);
  3307. Py_XDECREF(v);
  3308. v = PyLong_FromLong(arena->stats_freed_blocks);
  3309. PyDict_SetItemString(d, "freed_blocks", v ? v : Py_None);
  3310. Py_XDECREF(v);
  3311. v = PyLong_FromLong(arena->blocks_cached);
  3312. PyDict_SetItemString(d, "blocks_cached", v ? v : Py_None);
  3313. Py_XDECREF(v);
  3314. return d;
  3315. }
  3316. static PyObject *
  3317. _reset_stats(PyObject *self, PyObject *args) {
  3318. ImagingMemoryArena arena = &ImagingDefaultArena;
  3319. if (!PyArg_ParseTuple(args, ":reset_stats")) {
  3320. return NULL;
  3321. }
  3322. arena->stats_new_count = 0;
  3323. arena->stats_allocated_blocks = 0;
  3324. arena->stats_reused_blocks = 0;
  3325. arena->stats_reallocated_blocks = 0;
  3326. arena->stats_freed_blocks = 0;
  3327. Py_INCREF(Py_None);
  3328. return Py_None;
  3329. }
  3330. static PyObject *
  3331. _get_alignment(PyObject *self, PyObject *args) {
  3332. if (!PyArg_ParseTuple(args, ":get_alignment")) {
  3333. return NULL;
  3334. }
  3335. return PyLong_FromLong(ImagingDefaultArena.alignment);
  3336. }
  3337. static PyObject *
  3338. _get_block_size(PyObject *self, PyObject *args) {
  3339. if (!PyArg_ParseTuple(args, ":get_block_size")) {
  3340. return NULL;
  3341. }
  3342. return PyLong_FromLong(ImagingDefaultArena.block_size);
  3343. }
  3344. static PyObject *
  3345. _get_blocks_max(PyObject *self, PyObject *args) {
  3346. if (!PyArg_ParseTuple(args, ":get_blocks_max")) {
  3347. return NULL;
  3348. }
  3349. return PyLong_FromLong(ImagingDefaultArena.blocks_max);
  3350. }
  3351. static PyObject *
  3352. _set_alignment(PyObject *self, PyObject *args) {
  3353. int alignment;
  3354. if (!PyArg_ParseTuple(args, "i:set_alignment", &alignment)) {
  3355. return NULL;
  3356. }
  3357. if (alignment < 1 || alignment > 128) {
  3358. PyErr_SetString(PyExc_ValueError, "alignment should be from 1 to 128");
  3359. return NULL;
  3360. }
  3361. /* Is power of two */
  3362. if (alignment & (alignment - 1)) {
  3363. PyErr_SetString(PyExc_ValueError, "alignment should be power of two");
  3364. return NULL;
  3365. }
  3366. ImagingDefaultArena.alignment = alignment;
  3367. Py_INCREF(Py_None);
  3368. return Py_None;
  3369. }
  3370. static PyObject *
  3371. _set_block_size(PyObject *self, PyObject *args) {
  3372. int block_size;
  3373. if (!PyArg_ParseTuple(args, "i:set_block_size", &block_size)) {
  3374. return NULL;
  3375. }
  3376. if (block_size <= 0) {
  3377. PyErr_SetString(PyExc_ValueError, "block_size should be greater than 0");
  3378. return NULL;
  3379. }
  3380. if (block_size & 0xfff) {
  3381. PyErr_SetString(PyExc_ValueError, "block_size should be multiple of 4096");
  3382. return NULL;
  3383. }
  3384. ImagingDefaultArena.block_size = block_size;
  3385. Py_INCREF(Py_None);
  3386. return Py_None;
  3387. }
  3388. static PyObject *
  3389. _set_blocks_max(PyObject *self, PyObject *args) {
  3390. int blocks_max;
  3391. if (!PyArg_ParseTuple(args, "i:set_blocks_max", &blocks_max)) {
  3392. return NULL;
  3393. }
  3394. if (blocks_max < 0) {
  3395. PyErr_SetString(PyExc_ValueError, "blocks_max should be greater than 0");
  3396. return NULL;
  3397. } else if (
  3398. (unsigned long)blocks_max >
  3399. SIZE_MAX / sizeof(ImagingDefaultArena.blocks_pool[0])) {
  3400. PyErr_SetString(PyExc_ValueError, "blocks_max is too large");
  3401. return NULL;
  3402. }
  3403. if (!ImagingMemorySetBlocksMax(&ImagingDefaultArena, blocks_max)) {
  3404. return ImagingError_MemoryError();
  3405. }
  3406. Py_INCREF(Py_None);
  3407. return Py_None;
  3408. }
  3409. static PyObject *
  3410. _clear_cache(PyObject *self, PyObject *args) {
  3411. int i = 0;
  3412. if (!PyArg_ParseTuple(args, "|i:clear_cache", &i)) {
  3413. return NULL;
  3414. }
  3415. ImagingMemoryClearCache(&ImagingDefaultArena, i);
  3416. Py_INCREF(Py_None);
  3417. return Py_None;
  3418. }
  3419. /* -------------------------------------------------------------------- */
  3420. /* FIXME: this is something of a mess. Should replace this with
  3421. pluggable codecs, but not before PIL 1.2 */
  3422. /* Decoders (in decode.c) */
  3423. extern PyObject *
  3424. PyImaging_BcnDecoderNew(PyObject *self, PyObject *args);
  3425. extern PyObject *
  3426. PyImaging_BitDecoderNew(PyObject *self, PyObject *args);
  3427. extern PyObject *
  3428. PyImaging_FliDecoderNew(PyObject *self, PyObject *args);
  3429. extern PyObject *
  3430. PyImaging_GifDecoderNew(PyObject *self, PyObject *args);
  3431. extern PyObject *
  3432. PyImaging_HexDecoderNew(PyObject *self, PyObject *args);
  3433. extern PyObject *
  3434. PyImaging_JpegDecoderNew(PyObject *self, PyObject *args);
  3435. extern PyObject *
  3436. PyImaging_Jpeg2KDecoderNew(PyObject *self, PyObject *args);
  3437. extern PyObject *
  3438. PyImaging_LibTiffDecoderNew(PyObject *self, PyObject *args);
  3439. extern PyObject *
  3440. PyImaging_PackbitsDecoderNew(PyObject *self, PyObject *args);
  3441. extern PyObject *
  3442. PyImaging_PcdDecoderNew(PyObject *self, PyObject *args);
  3443. extern PyObject *
  3444. PyImaging_PcxDecoderNew(PyObject *self, PyObject *args);
  3445. extern PyObject *
  3446. PyImaging_RawDecoderNew(PyObject *self, PyObject *args);
  3447. extern PyObject *
  3448. PyImaging_SgiRleDecoderNew(PyObject *self, PyObject *args);
  3449. extern PyObject *
  3450. PyImaging_SunRleDecoderNew(PyObject *self, PyObject *args);
  3451. extern PyObject *
  3452. PyImaging_TgaRleDecoderNew(PyObject *self, PyObject *args);
  3453. extern PyObject *
  3454. PyImaging_XbmDecoderNew(PyObject *self, PyObject *args);
  3455. extern PyObject *
  3456. PyImaging_ZipDecoderNew(PyObject *self, PyObject *args);
  3457. /* Encoders (in encode.c) */
  3458. extern PyObject *
  3459. PyImaging_EpsEncoderNew(PyObject *self, PyObject *args);
  3460. extern PyObject *
  3461. PyImaging_GifEncoderNew(PyObject *self, PyObject *args);
  3462. extern PyObject *
  3463. PyImaging_JpegEncoderNew(PyObject *self, PyObject *args);
  3464. extern PyObject *
  3465. PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args);
  3466. extern PyObject *
  3467. PyImaging_PcxEncoderNew(PyObject *self, PyObject *args);
  3468. extern PyObject *
  3469. PyImaging_RawEncoderNew(PyObject *self, PyObject *args);
  3470. extern PyObject *
  3471. PyImaging_TgaRleEncoderNew(PyObject *self, PyObject *args);
  3472. extern PyObject *
  3473. PyImaging_XbmEncoderNew(PyObject *self, PyObject *args);
  3474. extern PyObject *
  3475. PyImaging_ZipEncoderNew(PyObject *self, PyObject *args);
  3476. extern PyObject *
  3477. PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args);
  3478. /* Display support etc (in display.c) */
  3479. #ifdef _WIN32
  3480. extern PyObject *
  3481. PyImaging_CreateWindowWin32(PyObject *self, PyObject *args);
  3482. extern PyObject *
  3483. PyImaging_DisplayWin32(PyObject *self, PyObject *args);
  3484. extern PyObject *
  3485. PyImaging_DisplayModeWin32(PyObject *self, PyObject *args);
  3486. extern PyObject *
  3487. PyImaging_GrabScreenWin32(PyObject *self, PyObject *args);
  3488. extern PyObject *
  3489. PyImaging_GrabClipboardWin32(PyObject *self, PyObject *args);
  3490. extern PyObject *
  3491. PyImaging_EventLoopWin32(PyObject *self, PyObject *args);
  3492. extern PyObject *
  3493. PyImaging_DrawWmf(PyObject *self, PyObject *args);
  3494. #endif
  3495. #ifdef HAVE_XCB
  3496. extern PyObject *
  3497. PyImaging_GrabScreenX11(PyObject *self, PyObject *args);
  3498. #endif
  3499. /* Experimental path stuff (in path.c) */
  3500. extern PyObject *
  3501. PyPath_Create(ImagingObject *self, PyObject *args);
  3502. /* Experimental outline stuff (in outline.c) */
  3503. extern PyObject *
  3504. PyOutline_Create(ImagingObject *self, PyObject *args);
  3505. extern PyObject *
  3506. PyImaging_MapBuffer(PyObject *self, PyObject *args);
  3507. static PyMethodDef functions[] = {
  3508. /* Object factories */
  3509. {"alpha_composite", (PyCFunction)_alpha_composite, METH_VARARGS},
  3510. {"blend", (PyCFunction)_blend, METH_VARARGS},
  3511. {"fill", (PyCFunction)_fill, METH_VARARGS},
  3512. {"new", (PyCFunction)_new, METH_VARARGS},
  3513. {"merge", (PyCFunction)_merge, METH_VARARGS},
  3514. /* Functions */
  3515. {"convert", (PyCFunction)_convert2, METH_VARARGS},
  3516. /* Codecs */
  3517. {"bcn_decoder", (PyCFunction)PyImaging_BcnDecoderNew, METH_VARARGS},
  3518. {"bit_decoder", (PyCFunction)PyImaging_BitDecoderNew, METH_VARARGS},
  3519. {"eps_encoder", (PyCFunction)PyImaging_EpsEncoderNew, METH_VARARGS},
  3520. {"fli_decoder", (PyCFunction)PyImaging_FliDecoderNew, METH_VARARGS},
  3521. {"gif_decoder", (PyCFunction)PyImaging_GifDecoderNew, METH_VARARGS},
  3522. {"gif_encoder", (PyCFunction)PyImaging_GifEncoderNew, METH_VARARGS},
  3523. {"hex_decoder", (PyCFunction)PyImaging_HexDecoderNew, METH_VARARGS},
  3524. {"hex_encoder", (PyCFunction)PyImaging_EpsEncoderNew, METH_VARARGS}, /* EPS=HEX! */
  3525. #ifdef HAVE_LIBJPEG
  3526. {"jpeg_decoder", (PyCFunction)PyImaging_JpegDecoderNew, METH_VARARGS},
  3527. {"jpeg_encoder", (PyCFunction)PyImaging_JpegEncoderNew, METH_VARARGS},
  3528. #endif
  3529. #ifdef HAVE_OPENJPEG
  3530. {"jpeg2k_decoder", (PyCFunction)PyImaging_Jpeg2KDecoderNew, METH_VARARGS},
  3531. {"jpeg2k_encoder", (PyCFunction)PyImaging_Jpeg2KEncoderNew, METH_VARARGS},
  3532. #endif
  3533. #ifdef HAVE_LIBTIFF
  3534. {"libtiff_decoder", (PyCFunction)PyImaging_LibTiffDecoderNew, METH_VARARGS},
  3535. {"libtiff_encoder", (PyCFunction)PyImaging_LibTiffEncoderNew, METH_VARARGS},
  3536. #endif
  3537. {"packbits_decoder", (PyCFunction)PyImaging_PackbitsDecoderNew, METH_VARARGS},
  3538. {"pcd_decoder", (PyCFunction)PyImaging_PcdDecoderNew, METH_VARARGS},
  3539. {"pcx_decoder", (PyCFunction)PyImaging_PcxDecoderNew, METH_VARARGS},
  3540. {"pcx_encoder", (PyCFunction)PyImaging_PcxEncoderNew, METH_VARARGS},
  3541. {"raw_decoder", (PyCFunction)PyImaging_RawDecoderNew, METH_VARARGS},
  3542. {"raw_encoder", (PyCFunction)PyImaging_RawEncoderNew, METH_VARARGS},
  3543. {"sgi_rle_decoder", (PyCFunction)PyImaging_SgiRleDecoderNew, METH_VARARGS},
  3544. {"sun_rle_decoder", (PyCFunction)PyImaging_SunRleDecoderNew, METH_VARARGS},
  3545. {"tga_rle_decoder", (PyCFunction)PyImaging_TgaRleDecoderNew, METH_VARARGS},
  3546. {"tga_rle_encoder", (PyCFunction)PyImaging_TgaRleEncoderNew, METH_VARARGS},
  3547. {"xbm_decoder", (PyCFunction)PyImaging_XbmDecoderNew, METH_VARARGS},
  3548. {"xbm_encoder", (PyCFunction)PyImaging_XbmEncoderNew, METH_VARARGS},
  3549. #ifdef HAVE_LIBZ
  3550. {"zip_decoder", (PyCFunction)PyImaging_ZipDecoderNew, METH_VARARGS},
  3551. {"zip_encoder", (PyCFunction)PyImaging_ZipEncoderNew, METH_VARARGS},
  3552. #endif
  3553. /* Memory mapping */
  3554. #ifdef WITH_MAPPING
  3555. {"map_buffer", (PyCFunction)PyImaging_MapBuffer, METH_VARARGS},
  3556. #endif
  3557. /* Display support */
  3558. #ifdef _WIN32
  3559. {"display", (PyCFunction)PyImaging_DisplayWin32, METH_VARARGS},
  3560. {"display_mode", (PyCFunction)PyImaging_DisplayModeWin32, METH_VARARGS},
  3561. {"grabscreen_win32", (PyCFunction)PyImaging_GrabScreenWin32, METH_VARARGS},
  3562. {"grabclipboard_win32", (PyCFunction)PyImaging_GrabClipboardWin32, METH_VARARGS},
  3563. {"createwindow", (PyCFunction)PyImaging_CreateWindowWin32, METH_VARARGS},
  3564. {"eventloop", (PyCFunction)PyImaging_EventLoopWin32, METH_VARARGS},
  3565. {"drawwmf", (PyCFunction)PyImaging_DrawWmf, METH_VARARGS},
  3566. #endif
  3567. #ifdef HAVE_XCB
  3568. {"grabscreen_x11", (PyCFunction)PyImaging_GrabScreenX11, METH_VARARGS},
  3569. #endif
  3570. /* Utilities */
  3571. {"getcodecstatus", (PyCFunction)_getcodecstatus, METH_VARARGS},
  3572. /* Special effects (experimental) */
  3573. #ifdef WITH_EFFECTS
  3574. {"effect_mandelbrot", (PyCFunction)_effect_mandelbrot, METH_VARARGS},
  3575. {"effect_noise", (PyCFunction)_effect_noise, METH_VARARGS},
  3576. {"linear_gradient", (PyCFunction)_linear_gradient, METH_VARARGS},
  3577. {"radial_gradient", (PyCFunction)_radial_gradient, METH_VARARGS},
  3578. {"wedge", (PyCFunction)_linear_gradient, METH_VARARGS}, /* Compatibility */
  3579. #endif
  3580. /* Drawing support stuff */
  3581. #ifdef WITH_IMAGEDRAW
  3582. {"font", (PyCFunction)_font_new, METH_VARARGS},
  3583. {"draw", (PyCFunction)_draw_new, METH_VARARGS},
  3584. #endif
  3585. /* Experimental path stuff */
  3586. #ifdef WITH_IMAGEPATH
  3587. {"path", (PyCFunction)PyPath_Create, METH_VARARGS},
  3588. #endif
  3589. /* Experimental arrow graphics stuff */
  3590. #ifdef WITH_ARROW
  3591. {"outline", (PyCFunction)PyOutline_Create, METH_VARARGS},
  3592. #endif
  3593. /* Resource management */
  3594. {"get_stats", (PyCFunction)_get_stats, METH_VARARGS},
  3595. {"reset_stats", (PyCFunction)_reset_stats, METH_VARARGS},
  3596. {"get_alignment", (PyCFunction)_get_alignment, METH_VARARGS},
  3597. {"get_block_size", (PyCFunction)_get_block_size, METH_VARARGS},
  3598. {"get_blocks_max", (PyCFunction)_get_blocks_max, METH_VARARGS},
  3599. {"set_alignment", (PyCFunction)_set_alignment, METH_VARARGS},
  3600. {"set_block_size", (PyCFunction)_set_block_size, METH_VARARGS},
  3601. {"set_blocks_max", (PyCFunction)_set_blocks_max, METH_VARARGS},
  3602. {"clear_cache", (PyCFunction)_clear_cache, METH_VARARGS},
  3603. {NULL, NULL} /* sentinel */
  3604. };
  3605. static int
  3606. setup_module(PyObject *m) {
  3607. PyObject *d = PyModule_GetDict(m);
  3608. const char *version = (char *)PILLOW_VERSION;
  3609. /* Ready object types */
  3610. if (PyType_Ready(&Imaging_Type) < 0) {
  3611. return -1;
  3612. }
  3613. #ifdef WITH_IMAGEDRAW
  3614. if (PyType_Ready(&ImagingFont_Type) < 0) {
  3615. return -1;
  3616. }
  3617. if (PyType_Ready(&ImagingDraw_Type) < 0) {
  3618. return -1;
  3619. }
  3620. #endif
  3621. if (PyType_Ready(&PixelAccess_Type) < 0) {
  3622. return -1;
  3623. }
  3624. ImagingAccessInit();
  3625. #ifdef HAVE_LIBJPEG
  3626. {
  3627. extern const char *ImagingJpegVersion(void);
  3628. PyObject *v = PyUnicode_FromString(ImagingJpegVersion());
  3629. PyDict_SetItemString(d, "jpeglib_version", v ? v : Py_None);
  3630. Py_XDECREF(v);
  3631. }
  3632. #endif
  3633. #ifdef HAVE_OPENJPEG
  3634. {
  3635. extern const char *ImagingJpeg2KVersion(void);
  3636. PyObject *v = PyUnicode_FromString(ImagingJpeg2KVersion());
  3637. PyDict_SetItemString(d, "jp2klib_version", v ? v : Py_None);
  3638. Py_XDECREF(v);
  3639. }
  3640. #endif
  3641. PyObject *have_libjpegturbo;
  3642. #ifdef LIBJPEG_TURBO_VERSION
  3643. have_libjpegturbo = Py_True;
  3644. {
  3645. #define tostr1(a) #a
  3646. #define tostr(a) tostr1(a)
  3647. PyObject *v = PyUnicode_FromString(tostr(LIBJPEG_TURBO_VERSION));
  3648. PyDict_SetItemString(d, "libjpeg_turbo_version", v ? v : Py_None);
  3649. Py_XDECREF(v);
  3650. #undef tostr
  3651. #undef tostr1
  3652. }
  3653. #else
  3654. have_libjpegturbo = Py_False;
  3655. #endif
  3656. Py_INCREF(have_libjpegturbo);
  3657. PyModule_AddObject(m, "HAVE_LIBJPEGTURBO", have_libjpegturbo);
  3658. PyObject *have_libimagequant;
  3659. #ifdef HAVE_LIBIMAGEQUANT
  3660. have_libimagequant = Py_True;
  3661. {
  3662. extern const char *ImagingImageQuantVersion(void);
  3663. PyObject *v = PyUnicode_FromString(ImagingImageQuantVersion());
  3664. PyDict_SetItemString(d, "imagequant_version", v ? v : Py_None);
  3665. Py_XDECREF(v);
  3666. }
  3667. #else
  3668. have_libimagequant = Py_False;
  3669. #endif
  3670. Py_INCREF(have_libimagequant);
  3671. PyModule_AddObject(m, "HAVE_LIBIMAGEQUANT", have_libimagequant);
  3672. #ifdef HAVE_LIBZ
  3673. /* zip encoding strategies */
  3674. PyModule_AddIntConstant(m, "DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY);
  3675. PyModule_AddIntConstant(m, "FILTERED", Z_FILTERED);
  3676. PyModule_AddIntConstant(m, "HUFFMAN_ONLY", Z_HUFFMAN_ONLY);
  3677. PyModule_AddIntConstant(m, "RLE", Z_RLE);
  3678. PyModule_AddIntConstant(m, "FIXED", Z_FIXED);
  3679. {
  3680. extern const char *ImagingZipVersion(void);
  3681. PyObject *v = PyUnicode_FromString(ImagingZipVersion());
  3682. PyDict_SetItemString(d, "zlib_version", v ? v : Py_None);
  3683. Py_XDECREF(v);
  3684. }
  3685. #endif
  3686. #ifdef HAVE_LIBTIFF
  3687. {
  3688. extern const char *ImagingTiffVersion(void);
  3689. PyObject *v = PyUnicode_FromString(ImagingTiffVersion());
  3690. PyDict_SetItemString(d, "libtiff_version", v ? v : Py_None);
  3691. Py_XDECREF(v);
  3692. // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7
  3693. PyObject *support_custom_tags;
  3694. #if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && \
  3695. TIFFLIB_VERSION != 20120922
  3696. support_custom_tags = Py_True;
  3697. #else
  3698. support_custom_tags = Py_False;
  3699. #endif
  3700. PyDict_SetItemString(d, "libtiff_support_custom_tags", support_custom_tags);
  3701. }
  3702. #endif
  3703. PyObject *have_xcb;
  3704. #ifdef HAVE_XCB
  3705. have_xcb = Py_True;
  3706. #else
  3707. have_xcb = Py_False;
  3708. #endif
  3709. Py_INCREF(have_xcb);
  3710. PyModule_AddObject(m, "HAVE_XCB", have_xcb);
  3711. PyObject *pillow_version = PyUnicode_FromString(version);
  3712. PyDict_SetItemString(d, "PILLOW_VERSION", pillow_version ? pillow_version : Py_None);
  3713. Py_XDECREF(pillow_version);
  3714. return 0;
  3715. }
  3716. PyMODINIT_FUNC
  3717. PyInit__imaging(void) {
  3718. PyObject *m;
  3719. static PyModuleDef module_def = {
  3720. PyModuleDef_HEAD_INIT,
  3721. "_imaging", /* m_name */
  3722. NULL, /* m_doc */
  3723. -1, /* m_size */
  3724. functions, /* m_methods */
  3725. };
  3726. m = PyModule_Create(&module_def);
  3727. if (setup_module(m) < 0) {
  3728. Py_DECREF(m);
  3729. return NULL;
  3730. }
  3731. return m;
  3732. }