Windows脚本编程核心技术精解Chapter21.pdf
Chapter 21Fax,Printer,Scanner,and GraphicsIn This Chapter?Discover Kodak Imaging and how you can control its functions by script?Check your TWAIN scanner support,select picture sources,and scan images?Automate scanning and scan in hundreds of images using batch automation?Print any image and create your own scan-print-photocopy tool?Scale printouts to fit the page?Load,print,and save any picture file?Rotate,scale,and zoom pictures,and create button faces from scannedimages automatically?Generate comprehensive thumbnail preview pages and organize your picture archives?Convert the graphics format and choose compression and color depth?Reveal compression settings and size information for any picture file,and repair picture file types automaticallyAll Windows versions come with a secret add-on called Kodak Imaging.Its fully scriptable,and in this chapter,you learn how to use it toscan images from a TWAIN scanner and to print or save the images.Say“Hi”to Kodak ImagingMicrosoft has included a tremendously useful tool in all 32-bit Windowsversions,and its called the Kodak Imaging tool(see Figure 21-1).This littletool hides in the Accessories program group(if its missing,you can justinstall it from your Windows CD by using the Control Panel Software moduleand choosing the Windows Setup tab).The Imaging tool is part of the base services offered by Windows.Just asWordPad gives you out-of-the-box access to WinWord documents,Imagingallows you to view graphics files,fax messages,and scan in pictures from anyTWAIN-compatible flatbed scanner.4684-8 ch21.f.qc 3/3/00 9:44 AM Page 581Figure 21-1:Kodak Imaging is a multi-purpose image viewing utility included with Windows.At first sight,the Imaging tool doesnt seem to be special,but it is.Its fullyscriptable.And it provides your scripts with new methods to read in picturesfrom any TWAIN picture source,as well as to print them out.A closer lookInternally,the Imaging tool consists of a number of COM objects,as shown inTable 21-1.Table 21-1Components of Kodak ImagingCOM ObjectDescriptionIMGADMIN.OCXAdministration toolIMGEDIT.OCXDisplay and print images,add notationsIMGSCAN.OCXTWAIN-compatible scanner supportIMGTHUMB.OCXThumbnail viewSome Windows versions come with a very detailed help file that provides allthe information necessary to script the components(see Figure 21-2).Searchfor IMGOCXD.HLP.Even if you dont find IMGOCXD.HLPon your system,youstill can retrieve all the methods and properties available.Just use script 5-12and enter the filenames listed above.582Part V:Accessing Hidden ComponentsII4684-8 ch21.f.qc 3/3/00 9:44 AM Page 582Figure 21-2:Kodak Imaging provides a full documentation.Getting access to the controlYou cant script the Kodak tools directly.Instead,you need to either embedthem into a Web page or use them as controls inside a custom COM object.As you might suspect,I have created a sample COM object.It basically wrapsthe controls and provides public methods and properties your script canaccess.Install installscansetup.exe(full source code is provided atcomponentsscanscan.vbp).Watch out because there are many different versions of Kodak Imaging around.If your source code wont compile and instead complains about illegal methods,then you need to replace the Imaging controls on the form with the controlsinstalled on your system.To do so,delete the controls from the form and then right-click the tool bar.Choose Components,and in the dialog box,click Browse.Now,search for thefiles listed in Table 21-1 and add them to your toolbar.At last,add thosecontrols back to your form.Now youre done.But theres an even easier way.You can install the pre-built COM objectwithout recompiling it.A word of cautionTake a look at the COM object source code.Its not complicatedthe Imagingtool handles the difficult parts.Still,you need to be aware of some very impor-tant design rules.Chapter 21:Fax,Printer,Scanner,and Graphics583II4684-8 ch21.f.qc 3/3/00 9:44 AM Page 583The COM object places the Imaging controls on a separate form.This is doneso you can display the edit control as a dialog box.However,theres a strictrulealways place the code managing the controls into the same object thathosts the controls.If you dont,you may experience protection faults andblue screens.The reason is simple.The form may be unloaded in the event of an error.Thecontrols arent there anymore because they“lived”inside the form.If some otherpart of your COM object still tries to access the controls,it will send data to amemory address thats no longer valid,making the protection fault necessary.Still,you need code in the User Control because this is the only place you canmake internal functions accessible to the outside world.However,the code inthe User Control only“wraps”the code defined in the form.This is okay.Justmake sure all the complex parts are in the same object together with theImaging controls they refer to.Finding out if TWAIN support is availableKodak Imaging requires that TWAIN software be installed on your system(see Figure 21-3).Most scanners and a lot of other imaging sources come with TWAIN drivers.To make sure,use your new COM object and find out:Figure 21-3:Find out whether you have TWAIN support.21-1.VBSset tool=CreateObject(“twain.manager”)ok=tool.ScannerAvailableif ok thenMsgBox“TWAIN support is installed.Check out your scan sources!”tool.SelectScannerelseMsgBox“No TWAIN support detected.Get a“_&“TWAIN-compliant Scanner!”,vbExclamationend ifIf TWAIN support is detected,the script calls SelectScanner.This invokes abuilt-in dialog box that lists all TWAIN-compliant imaging sources available.Ifno TWAIN support was detected,you cant proceed.Get a TWAIN-compliantimaging device first.Although many different imaging devices can be controlled via TWAIN,theKodak Imaging tool specializes in scanners.You may or may not be able touse a digital camera or other devices.Non-compliant devices generate benignerror messages.584Part V:Accessing Hidden ComponentsII4684-8 ch21.f.qc 3/3/00 9:44 AM Page 584Scanning PicturesWith the help of your new COM component,your scripts can now scan pages.There are many useful real-world tasks you can now master.For example,youcan create your own little photocopy machine,or you can batch-scan a wholeseries of pictures without having to click too many buttons.Saving scanned pictures to diskThe next script shows how to scan a picture and save it to disk.The script ispretty straightforward because it leaves the difficult stuff to the Imaging tool:21-2.VBSset tool=CreateObject(“twain.manager”)check whether twain support is availableif not tool.ScannerAvailable thenMsgBox“No TWAIN support!”,vbCriticalWScript.Quitend if fill in informationfilename=“C:mypic.jpg”scan and save as bmp graphictool.FileType=3 1:TIFF(default)2:AWD(Win 98 Fax format)3:BMP tell control how to storetool.PageOption=6 0:create new picture.Error if picture already exists 1:create new picture.Ask if picture already exists(default)2:append to existing picture 3:insert into existing picture at position specified by page 4:overwrite existing picture.If picture doesnt exist,error 5:overwrite existing picture,ask for permission.Error if picture doesnt yet exist 6:always overwrite tell control how to scantool.ScanTo=1 0:display image only(default)1:display and write to disk 2:write to disk 3:write to disk using template and display 4:write to disk using template 5:fax image(fax software must be installed)show scanner setup?tool.ShowSetup=trueChapter 21:Fax,Printer,Scanner,and Graphics585II4684-8 ch21.f.qc 3/3/00 9:44 AM Page 585 show quality dialog?tool.ShowScanPreferences ok,scan pagetool.ScanPage(filename)now,display the scanned page in your favorite drawing programset wshshell=CreateObject(“WScript.Shell”)wshshell.run“”&filename&“”This script scans in a page and displays it in your favorite drawing program.Runlaunches the file you scanned and then passes it to the programassociated with its file type.If theres no program associated,Runfails.The dialog boxes all come from your TWAIN scanner driver.They may lookdifferent on your system.Most scan dialog boxes feature a preview function.You can select part of the pre-scanned image and scan only the selected area.Note,however,that sometimes dialog boxes may be hidden behind otherunnecessary windows,so its a good idea to close them.The reason for thisodd behavior is obviousyou are calling another process,and beginning withWindows 98,Microsoft doesnt allow external processes to focus their ownwindows as they please.But youve already seen how you can work aroundthis issue.All you need to do is to decrease the focus lock time to zero.Figure 21-4:The scanner dialog box may look different and is provided by your TWAIN driver.Automated scanningThe previous script displays all kinds of scan dialog boxes.Scan dialog boxesgive you very detailed control over the scan quality,but you might want to586Part V:Accessing Hidden ComponentsII4684-8 ch21.f.qc 3/3/00 9:44 AM Page 586automate scanning.First try to scan with the built-in defaults and see if itworks(see Figure 21-5):21-3.VBSset tool=CreateObject(“twain.manager”)check whether twain support is availableif not tool.ScannerAvailable thenMsgBox“No TWAIN support!”,vbCriticalWScript.Quitend iffilename=“C:mypic.jpg”tool.FileType=3tool.PageOption=6tool.ScanTo=1tool.ShowSetup=falsetool.ScanPage(filename)set wshshell=CreateObject(“WScript.Shell”)wshshell.run“”&filename&“”You may not be pleased with the default values.However,theres no way to set color options and other scan quality related issues remotely.You have twochoices.One,you can display the official scan dialog box once,using ShowSetup=true.For all subsequent scans,you should turn the dialog off.Your scannerwill now use the settings you chose in the dialog box for as long as your scriptruns.Or two,you can use SendKeysto automate any dialog box.Refer toChapter 10 to find out how to switch to dialog boxes and send keystrokes.Figure 21-5:The script can open the scanned picture only if you have drawing softwareinstalled.Chapter 21:Fax,Printer,Scanner,and Graphics587II4684-8 ch21.f.qc 3/3/00 9:44 AM Page 587Scanning large numbers of picturesPerhaps you want to scan in a whole lot of pictures.For example,you mightwant to digitize some paperwork or put your family photo gallery onto yourWeb site.Scripts are the perfect solution.In addition,the Imaging tool supportstemplate scanning.Template scanning means the tool automatically createsfilenames with serial numbers.Get yourself a document feeder.This way,scanning is truly automated,andyou dont even need to place the pictures on your scanner anymore.The next script scans as many pictures as you like and assigns uniquefilenames:21-4.VBSset tool=CreateObject(“twain.manager”)check whether twain support is availableif not tool.ScannerAvailable thenMsgBox“No TWAIN support!”,vbCriticalWScript.Quitend iffilename=“C:picspic”bmptool.FileType=3 overwritetool.PageOption=6 template scantool.ScanTo=4 show setup for first picture scantool.ShowSetup=truedotool.ScanPage(filename)dont show setup for rest of scanstool.ShowSetup=falsemsg=“Scan completed!Scan another picture?”answer=MsgBox(msg,vbYesNo+vbQuestion)loop until answer=vbNoMsgBox“Done.”The script invokes the scanning user interface only once:This way,you canspecify the scan options.Your scanner uses these settings for all subsequentscans.Note that this time the script doesnt specify a filename.Instead,itprovides a filename template.The Imaging tool stores all pictures in the folderC:pics and uses pic as template.The individual files are called pic00000.jpg,pic00001.jpg,etc.Make sure the folder you want to store the pictures in really exists.If its missing,the script will complain.588Part V:Accessing Hidden ComponentsII4684-8 ch21.f.qc 3/3/00 9:44 AM Page 588Scanning pictures with the preview functionThe Imaging components can do much more than just scanning.If you wantto,you can use the edit control to display scanned images and use the thumbcontrol to show thumbnail previews of scanned pictures.However,thesefeatures are a different story.The COM component demonstrates how to link a scan control to the editcontrol.This allows for actually viewing the scan as it takes place(see Figure21-6).Make sure you have set ShowSetupto false because otherwise theofficial scan dialog box will cover your own scanning preview.21-5.VBSset tool=CreateObject(“twain.manager”)check whether twain support is availableif not tool.ScannerAvailable thenMsgBox“No TWAIN support!”,vbCriticalWScript.Quitend iffilename=“C:mypic.jpg”tool.FileType=3tool.PageOption=6tool.ScanTo=1tool.ShowSetup=falsetool.Width=600tool.Height=400tool.ScanPageUI(filename)set wshshell=CreateObject(“WScript.Shell”)wshshell.run“”&filename&“”The preview window closes automatically after scanning is complete.If youwant,you can easily change the COM source code to provide an additionalClose button.Figure 21-6:Watch the scan happen:The custom dialog box shows the scan in real-time.Chapter 21:Fax,Printer,Scanner,and Graphics589II4684-8 ch21.f.qc 3/3/00 9:44 AM Page 589Because we are talking about scripts,and scripts are all about automation,your dialog box needs to close without user interaction.You can set the size of your preview window to anything you like.Use the Width and Height properties.Printing Scanned ImagesScanning pictures is a cool feature,but its only partially useful if you cantprint your scanned images.Fortunately,the Imaging control provides printingcapabilities,too.Your personal photocopy machineSave your trips to the copy shop.Instead,tie together your scanner and yourprinter,and create your own photocopy machine.If you own a color printer,you can even copy in full-color.If you install some fax software,you can printto the faxmodem and get a“real”fax machine.21-6.VBSset tool=CreateObject(“twain.manager”)check whether twain support is availableif not tool.ScannerAvailable thenMsgBox“No TWAIN support!”,vbCriticalWScript.Quitend iffilename=“C:mypic.jpg”tool.FileType=3tool.PageOption=6tool.ScanTo=1tool.ShowSetup=truetool.Width=600tool.Height=400tool.ScanPageUI(filename)tool.PrintImageThis is all you need.PrintImageprints the scanned image to your defaultprinter and scales the picture to fit the page.If you want to select printeroptions first,use PrintImageUIinstead.This displays the usual printer dialogbox(see Figure 21-7).The printer dialog box has a special Option button thatallows you to choose between different scale modes(see Figure 21-8).590Part V:Accessing Hidden ComponentsII4684-8 ch21.f.qc 3/3/00 9:44 AM Page 590Figure 21-7:Use the official print dialog box to print your images.Figure 21-8:Your print dialog box may look different:You can always expand the image full-page.Chapter 21:Fax,Printer,Scanner,and Graphics591II4684-8 ch21.f.qc 3/3/00 9:44 AM Page 591You can specify the scale modes with PrintImage,too.Use the values shownin Table 21-2.Table 21-2Printer OptionsValueDescription0Print image 1:1(image appears smaller than original bec