DIBs and Their Use.docx
《DIBs and Their Use.docx》由会员分享,可在线阅读,更多相关《DIBs and Their Use.docx(17页珍藏版)》请在冰豆网上搜索。
DIBsandTheirUse
DIBsandTheirUse
RonGery
MicrosoftDeveloperNetworkTechnologyGroup
March20,1992
Clicktovieworcopythesampleapplicationfilesforthistechnicalarticle.
Abstract
ThisarticlediscussestheDIB(device-independentbitmap)conceptfromdefinitionandstructuretotheAPIthatusesit.IncludedisasmallsampleapplicationthatillustratessomeofthemostcommonmethodsofusingDIBstodisplayandmanipulatedigitalimages.Functionsdiscussedare GetDIBits, SetDIBits, CreateDIBitmap, SetDIBitsToDevice, StretchDIBits,and CreateDIBPatternBrush.ThisarticledoesnotdiscussusingpaletteswithDIBs.
Overview
ADIB(device-independentbitmap)isaformatusedtodefinedevice-independentbitmapsinvariouscolorresolutions.ThemainpurposeofDIBsistoallowbitmapstobemovedfromonedevicetoanother(hence,thedevice-independentpartofthename).ADIBisan external format,incontrasttoadevice-dependentbitmap,whichappearsinthesystemasabitmapobject(createdbyanapplicationusing CreateBitmap, CreateCompatibleBitmap, CreateBitmapIndirect,orCreateDIBitmap).ADIBisnormallytransportedinmetafiles(usuallyusingthe StretchDIBits function),BMPfiles,andtheClipboard(CF_DIBdataformat).
ADIBconsistsoftwoparts:
thebitsthemselvesandaheaderthatdescribestheformatofthebits.Theheadercontainsthecolorformat,acolortable,andthesizeofthebitmap.ThecurrentDIBformatsupportsfourcolorresolutions:
1bit,4bit,8bit,and24bit.In1-bit,4-bit,and8-bitDIBs,thepixelsaredefinedbyindexes(oftheappropriatebitresolution)intothecolortable;24-bitpixelsaredescribedas24-bitvalues,1byteeachforred,green,andblue.
TheDIBfunctionsare:
GetDIBits
Translatesadevice-dependentbitmapintotheDIBformat
SetDIBits
TranslatesaDIB'sinformationintodevice-dependentform
CreateDIBitmap
Createsadevice-dependentbitmapinitializedwithDIBinformation
SetDIBitsToDevice
SetsaDIBdirectlytotheoutputsurface
StretchDIBits
MovesarectanglefromtheDIBtoarectangleonthedestinationsurface,stretchingorcompressingasnecessary
CreateDIBPatternBrush
CreatesapatternbrushusingaDIBforthebitmapdescription
DeviceIndependence—What'sItGoodFor?
TransferringcolorbitmapsfromonedevicetoanotherwasnotpossibleinversionsoftheMicrosoft®Windows™graphicalenvironmentearlierthan3.0.WithDIBs,eachdevicedisplaystheimagetotheabilityofitscolorresolution.AnapplicationcanstoreanimageintheDIBformatandthendisplayit,regardlessoftheoutputdevice;anapplicationneednolongercreateaversionofeachimageforeachtypeofdevice.
Thisimagetransferabilitycanbeusedtoprinthalftoneimages.Forexample,the StretchDIBits functioncanpassaDIBdirectlytoanintelligentprinterdriver.Giventhefullcolorinformationoftheimageinsteadofsimplyamonochromeversion(thetraditionalmethod),thedrivercanusehalftonestoprintarealisticpicture.
BecausetheDIBformatispubliclydefined,anapplicationcanmanipulateitonthefly.Infact,anapplicationcanbuildanimagewithoutanyinteractionwithWindows.IfWindowslacksadrawingprimitive,theapplicationcansimulateitdirectlyintotheDIBinsteadofusingtheexistinggraphicsdeviceinterface(GDI)primitives.Unfortunately,underWindowsversions3.0and3.1,GDIcannotperformoutputoperationsdirectlytoaDIB.
BMPFileFormats
ThefileextensionofaWindowsDIBfileisBMP.Thefileconsistsofa BITMAPFILEHEADER structurefollowedbytheDIBitself.Unfortunately,becausethe BITMAPFILEHEADER structureisneveractuallypassedtotheAPI,noteveryapplicationthatgeneratesBMPfilesfillsoutthedatastructurecarefully.Toaddtothisconfusion,the"proper"definitionofthestructureisatoddswiththedocumentation.Properly,thedatastructurecontainsthefollowingfields:
bfType
A WORD thatdefinesthetypeoffile.Itmustbe'BM'.
bfSize
A DWORD thatspecifiesthesizeofthefileinbytes.TheMicrosoftWindowsSoftwareDevelopmentKit(SDK)documentationclaimsotherwise.Tobeonthesafeside,manyapplicationscalculatetheirownsizesforreadinginafile.
bfReserved1,bfReserved2
WORDsthatmustbesetto0.
bfOffBits
A DWORD thatspecifiestheoffsetfromthebeginningofthe BITMAPFILEHEADER structuretothestartoftheactualbits.TheDIBheaderimmediatelyfollowsthefileheader,buttheactualimagebitsneednotbeplacednexttotheheadersinthefile.
TheDIBheaderimmediatelyfollowsthe BITMAPFILEHEADER structure.
ForacodesamplethatreadsaBMPfile,seethesampleprogram.
TheDIBHeader
Theheaderactuallyconsistsoftwoadjoiningparts:
theheaderproperandthecolortable.Botharecombinedinthe BITMAPINFO structure,whichiswhatallDIBAPIsexpect.
Windowssupportstwovarietiesofheaders:
BITMAPINFOHEADER and BITMAPCOREHEADER.Ifatallpossible,applicationsshoulduseonly BITMAPINFOHEADERs.The BITMAPCOREHEADER definitionisbasedonthebitmapdefinitionfromPresentationManager™version1.1andissupportedforcompatibility.
DuringaDIBsettingoperation,mostfieldsarealreadyfilledinbywhoevergeneratedtheDIB.Doinga GetDIBits call,however,providesmorecontrol.ThewaytheheaderisfilledinforthisoperationdefinestheresultingDIB,particularlyitscolorresolution.
BITMAPINFOHEADER containsthefollowingfields:
biSize
Shouldbesetto sizeof(BITMAPINFOHEADER).Thisfielddefinesthesizeoftheheader(minusthecolortable).IfanewDIBdefinitionisadded,itisidentifiedbyanewvalueforthesize.Thisfieldisalsoconvenientforcalculatingapointertothecolortable,whichimmediatelyfollowsthe BITMAPINFOHEADER.
biWidth,biHeight
Definethewidthandtheheightofthebitmapinpixels.Theyare DWORD valuesforfutureexpansion,andthecodeinWindowsversions3.0and3.1ignoresthehighword(whichshouldbesetto0).
biPlanes
Shouldalwaysbe1.AllDIBdefinitionsrelyon biBitCount fordefiningthecolorresolution.
biBitCount
Definesthecolorresolution(inbitsperpixel)oftheDIB.Onlyfourvaluesarevalidforthisfield:
1,4,8,and24.Newresolutions(16bit,forexample)maybeaddedinthefuture,butfornowonlythesefourdefineavalidDIB.Choosingtheappropriatevaluewhendoinga GetDIBits isdiscussedbelow.Whenperforminga Set operation,thevalueshouldalreadybedefinedforthebits.
biCompression
Specifiesthetypeofcompression.Canbeoneofthreevalues:
BI_RGB,BI_RLE4,orBI_RLE8.Themostcommonandusefulchoice,BI_RGB,definesaDIBinwhichallisasitseems.Eachblockof biBitCount bitsdefinesanindex(orRGBvaluefor24-bitversions)intothecolortable.TheothertwooptionsspecifythattheDIBisstored(orwillbestored)usingeitherthe4-bitorthe8-bitrunlengthencoding(RLE)schemethatWindowssupports.TheRLEformatsareespeciallyusefulforanimationapplicationsandalsousuallycompressthebitmap.BI_RGBformatisrecommendedforalmostallpurposes.RLEversions,althoughpossiblysmaller,areslowertodecode,notaswidelysupported,andextremelypainfultobandproperly.
biSizeImage
Containsthesizeofthebitmapproperinbytesorthevalue0.Avalueof0indicatesthattheDIBisofdefaultsize.Calculatingthesizeofabitmapisnotdifficult:
biSizeImage=((((biWidth*biBitCount)+31)&
~31)>>3)*biHeight:
Thecrazyroundoffsandshiftsaccountforthebitmapbeing DWORD-alignedattheendofeveryscanline.Whennonzero,thisfieldtellsanapplicationhowmuchstoragespacetheDIB'sbitsneed.The biSizeImagefieldreallybecomesusefulwhendealingwithanRLEbitmap,thesizeofwhichdependsonhowwellthebitmapwasencoded.IfanRLEbitmapistobepassedaround,the biSizeImage fieldismandatory.
biXPelsPerMeter,biYPelsPerMeter
Defineapplication-specifiedvaluesforthedesirabledimensionsofthebitmap.Thisinformationcanbeusedtomaintainthephysicaldimensionsofanimageacrossdevicesofdifferentresolutions.GDInevertouchesthesefields.Whennotfilledin,theyshouldbothbesetto0.
biClrUsed
Providesawayforgettingsmallercolortables.Whenthisfieldissetto0,thenumberofcolorsinthecolortableisbasedonthe biBitCount field(1indicates2colors,4indicates16,8indicates256,and24indicatesnocolortable).Anonzerovaluespecifiestheexactnumberofcolorsinthetable.So,forexample,ifan8-bitDIBusesonly17colors,thenonlythose17colorsneedtobedefinedinthetable,and biClrUsed issetto17.Ofcourse,nopixelcanhaveanindexpointingpasttheendofthetable.
Note:
Thisfieldcannotbeusedduringa GetDIBits operation.GDIalwaysfillsafull-sizecolortable.Thefieldisthereforemoreusefulforpost-processingoperations,whenanapplicationtrimsdownthecontentsoftheDIB.Ifnonzerofora24-bitDIB,itindicatestheexistenceofacolortablethattheapplicationcanuseforcolorreference.
biClrImportant
Specifiesthatthefirst x colorsofthecolortableareimportanttotheDIB.Iftherestofthecolorsarenotavailable,theimagestillretainsitsmeaninginanacceptablemanner.biClrImportantispurelyforapplicationuse;GDIdoesnottouchthisvalue.Whenthisfieldissetto0,allthecolorsareimportant,or,rather,theirrelativeimportancehasnotbeencomputed.
Thecolortableimmediatelyfollowstheheaderinformation.Nocolortableisdefinedfor24-bitDIBs.Thetableconsistsofanarrayof RGBQUAD datastructures.(Thetableforthe BITMAPCOREINFO formatisbuiltwiththe RGBTRIPLEdata structure.)Red,green,andbluebytesare inreverseorder (redswapspositionwithblue)fromtheWindowsconventio