Tải bản đầy đủ - 0 (trang)
Chapter 13. Image Magic: Programming and Power Tools

Chapter 13. Image Magic: Programming and Power Tools

Tải bản đầy đủ - 0trang

Thischapter,aswiththerestofthisbook,focuses

onPHPastheprogramminglanguage,primarily

becausePHPistheeasiestwebscriptinglanguage

toreadforthosenotasfamiliarwithsoftware

development.



13.1.ServingUpPhotos:InstaSlideshows

Itmightsurpriseyouhowmuchyoucanmanipulateimages

usingserver-sidetechnology.Notjusthowimagesaredisplayed

onapage,butthefactthatyoucaneasilyopenanimagefile,

manipulateitscontents,andgenerateanentirelynewimageas

aresult.

Theonlylimitationtothistypeofimagefunctionalityisthefact

thatphotoandgraphicsmanipulationisheavilymathematicalin

nature,andassuch,canputaburdenonthehostingmachine's

CPUandmemory.However,formostofus,andmostofour

needs,serverscaneasilyhandletheextraload.Youmightwant

torestrictaccesstoeditingorconversionapplications,though.

Oneofthesimplestusesofserver-sidefunctionalityistocreate

adrop-ininsta-slideshow.Thistypeofapplicationcanexamine

allthephotosinadirectoryandinstantlygeneratethe

necessarynavigationcontrols.Iprovidedjustsuchan

applicationformytechreviewers,tomakeiteasiertoreview

thefiguresforthisbook.

Thefirstcomponenttotheapplicationiscodetoopenthe

currentdirectory,lookforallfilenameswithfileextensions

providedin$exts,andthencreateasortedarrayofthese

filenames.Example13-1showsthisfunctionality,createdasa

separatePHPfile,photos.php.It'screatedseparatelysothat

thefunctionalitycanbeusedinmultipleapplications.The

currentversionjustcreatesthearray,butotherversionscould



encapsulatethefunctionalityintoanobjectmethodormakeit

accessibleviaanexternallibraryfunction.

Example13-1.Functionalitytocreateanarrayfromfiles

inadirectory


$exts=array('jpg','png','gif');

//collectlistofimagesincurrent(look)directory

$url=array();

if($handle=opendir(dirname(__FILE__))){

while(false!==($image=readdir($handle)))

foreach($extsas$ext)

if(strstr($image,'.'.$ext))

$photos[]=$image;

closedir($handle);

}

sort($photos);



?>



There'snothingspecificallyimage-relatedtothefunctionalityin

photos.php;itcouldbeusedforfileswithanyextensionjustby

changingtheentriesinthe$extsarray:

$exts=array('jpeg','pdf');



Thenextpieceoftheapplicationistheslideshowpageitself,

slideshow.php,asshowninExample13-2.Itincludesa

referencetothephotos.phpfileatthetop,andthenreadsthe



currentphoto(ifany)fromtheURL(viathephotoparameter).

Fromthisinformation,theapplicationrebuildstheappropriate

navigation,checkingfirsttoseewhetheritmakessenseto

showthePreviousorNextbuttons.Iftheviewerisatthelastof

thephotosinthedirectory,theNextbuttonisn'tshown;atthe

first,thePreviousbuttonisnotdisplayed.

Example13-2.Slideshowapplicationpage,including

codetocreatethenavigation

CodeView:


require_once"photos.php";

$index=$_GET['photo'];

$uri=$_SERVER['SCRIPT_NAME'];

if(empty($index))

$index=0;

$prev=$index-1;

if($index<(count($photos)-1)){

$next=$index+1;

}



?>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">





Slideshow










=0):?>



">Pr
















">Ne













"id="photo"al

$photos[$index];?>"/>



































Theapplicationcreatesthenavigationbar,whichbasicallyjust

printsoutthearrayentryphotonumberforthenextand

previousphoto,anddisplayswhateverphotoiscurrent:either

thefirstwhenthepageisopened,orwhicheverphotoisnextin

thenavigationstream.



Figure13-1showstheapplicationinprocess.Thepageisstyled

throughtheuseofCSS,includedasaseparatefileandnot

repeatedhere.Theexamplefilesforthebookincludeallofthe

necessaryfilesforthisapplication.

Toruntheapplication,allyouhavetodoisdropthe

photos.php,slideshow.php,andphotoslideshow.cssfilesinto

thedirectorywheretheimagesarestored,and,instantly,you

haveaslideshow.

Renametheslideshow.phpfiletoindex.php,and

youalsopreventa"directorycontents"viewof

theimagedirectory.Securityandslideshowin

one.



Chapter13.ImageMagic:Programming

andPowerTools

Thereareanextraordinarynumberoftoolsthatcancreateand

manipulateimagesonthetypicalLinux-basedwebserver.From

nativeimagesupportbuiltintoprogramminglanguagestotools

thatcanbeaccessedviathecommandline,youcanturna

photointoapostcard,resizeandannotateimages,createan

instantslideshow,ortossincompleximagemanipulationsat

thecallofafunction.

Forinstance,popularwebscriptinglanguagessuchasPHPhave

built-ininterfacestoexternalgraphicslibraries.Withthis

support,wecancreatesimpleapplicationsthatcanopena

photo,accessindividualpixelstofindcolorsatthesepoints,

andgenerateanentirewebcolorscheme.

Goingbeyondthisbuilt-inlanguage-basedfunctionality,there's

theincrediblypowerfulImageMagicksoftwaresuit,with

functionalitythatcanbeaccessedviathecommandline,built

intoreusablescripts,orcreatedasapplicationsvialibrariesin

PHP,Perl,Ruby,andPython,amongothers.

Mostofthefunctionalitycoveredinthischapterisavailablewith

thetypicalweb-hostingpackagethatprovidesSecureShell

(SSH)access,andisbuiltintotheLinuxoperatingsystem.Most

isalsoavailableeasilyontheMacwiththeMacportspackage

managementsystemorcomparableFinksystem.Inaddition,

theversionofPHPforWindowsincludesaccesstothegraphics

functionality,andImageMagickprovidesaone-clickinstallation

ofthegraphicssuiteforWindows.

Theonlyrestrictiontothesegraphicscapabilitiesisthattheydo

requiresomeprogrammingexperienceandalevelofcomfort

withtheLinuxorMS-DOScommandline.However,noneofthe

capabilitiesrequiresthatapersonbeaproatsoftware

developmentorawizatUnix.Astronginterestandcuriosity

aretheprimaryrequirements.



Thischapter,aswiththerestofthisbook,focuses

onPHPastheprogramminglanguage,primarily

becausePHPistheeasiestwebscriptinglanguage

toreadforthosenotasfamiliarwithsoftware

development.



13.1.ServingUpPhotos:InstaSlideshows

Itmightsurpriseyouhowmuchyoucanmanipulateimages

usingserver-sidetechnology.Notjusthowimagesaredisplayed

onapage,butthefactthatyoucaneasilyopenanimagefile,

manipulateitscontents,andgenerateanentirelynewimageas

aresult.

Theonlylimitationtothistypeofimagefunctionalityisthefact

thatphotoandgraphicsmanipulationisheavilymathematicalin

nature,andassuch,canputaburdenonthehostingmachine's

CPUandmemory.However,formostofus,andmostofour

needs,serverscaneasilyhandletheextraload.Youmightwant

torestrictaccesstoeditingorconversionapplications,though.

Oneofthesimplestusesofserver-sidefunctionalityistocreate

adrop-ininsta-slideshow.Thistypeofapplicationcanexamine

allthephotosinadirectoryandinstantlygeneratethe

necessarynavigationcontrols.Iprovidedjustsuchan

applicationformytechreviewers,tomakeiteasiertoreview

thefiguresforthisbook.

Thefirstcomponenttotheapplicationiscodetoopenthe

currentdirectory,lookforallfilenameswithfileextensions

providedin$exts,andthencreateasortedarrayofthese

filenames.Example13-1showsthisfunctionality,createdasa

separatePHPfile,photos.php.It'screatedseparatelysothat

thefunctionalitycanbeusedinmultipleapplications.The

currentversionjustcreatesthearray,butotherversionscould



encapsulatethefunctionalityintoanobjectmethodormakeit

accessibleviaanexternallibraryfunction.

Example13-1.Functionalitytocreateanarrayfromfiles

inadirectory


$exts=array('jpg','png','gif');

//collectlistofimagesincurrent(look)directory

$url=array();

if($handle=opendir(dirname(__FILE__))){

while(false!==($image=readdir($handle)))

foreach($extsas$ext)

if(strstr($image,'.'.$ext))

$photos[]=$image;

closedir($handle);

}

sort($photos);



?>



There'snothingspecificallyimage-relatedtothefunctionalityin

photos.php;itcouldbeusedforfileswithanyextensionjustby

changingtheentriesinthe$extsarray:

$exts=array('jpeg','pdf');



Thenextpieceoftheapplicationistheslideshowpageitself,

slideshow.php,asshowninExample13-2.Itincludesa

referencetothephotos.phpfileatthetop,andthenreadsthe



currentphoto(ifany)fromtheURL(viathephotoparameter).

Fromthisinformation,theapplicationrebuildstheappropriate

navigation,checkingfirsttoseewhetheritmakessenseto

showthePreviousorNextbuttons.Iftheviewerisatthelastof

thephotosinthedirectory,theNextbuttonisn'tshown;atthe

first,thePreviousbuttonisnotdisplayed.

Example13-2.Slideshowapplicationpage,including

codetocreatethenavigation

CodeView:


require_once"photos.php";

$index=$_GET['photo'];

$uri=$_SERVER['SCRIPT_NAME'];

if(empty($index))

$index=0;

$prev=$index-1;

if($index<(count($photos)-1)){

$next=$index+1;

}



?>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">





Slideshow










=0):?>



">Pr
















">Ne













"id="photo"al

$photos[$index];?>"/>



































Theapplicationcreatesthenavigationbar,whichbasicallyjust

printsoutthearrayentryphotonumberforthenextand

previousphoto,anddisplayswhateverphotoiscurrent:either

thefirstwhenthepageisopened,orwhicheverphotoisnextin

thenavigationstream.



Figure13-1showstheapplicationinprocess.Thepageisstyled

throughtheuseofCSS,includedasaseparatefileandnot

repeatedhere.Theexamplefilesforthebookincludeallofthe

necessaryfilesforthisapplication.

Toruntheapplication,allyouhavetodoisdropthe

photos.php,slideshow.php,andphotoslideshow.cssfilesinto

thedirectorywheretheimagesarestored,and,instantly,you

haveaslideshow.

Renametheslideshow.phpfiletoindex.php,and

youalsopreventa"directorycontents"viewof

theimagedirectory.Securityandslideshowin

one.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 13. Image Magic: Programming and Power Tools

Tải bản đầy đủ ngay(0 tr)

×