请问icon的图像文件格式是怎样的?(50分)

  • 主题发起人 主题发起人 Tenlic
  • 开始时间 开始时间
T

Tenlic

Unregistered / Unconfirmed
GUEST, unregistred user!
我是想编程得到其他程序里面的图标。
 
和BMP基本是一样的,要得到其它程序里面的图标,就要读取它的资源
 
好象有API函数可以直接得到,网上有例子,好好找找
 
去看看图表猎手的源代码吧,里面有,我也整理了一个单元,封装成了函数,只要给出文件名和
图表索引号,就可以提取真彩色的图标~~~~~~~~~~~~~~~~~~~~
 
to kingron:
把你的封装的函数发上来看看好码??
 
有问题了
 
to Kingron,
需要你的帮忙了!谢谢,能不能把那个函数email给小弟!jbas@163.com
 
我Post出来吧:
///文件名:Icons.Pas
unit Icons;

interface

uses windows, sysutils;

type
PByte = ^Byte;
PBitmapInfo = ^BitmapInfo;

/// These first two structs represent how the icon information is stored
/// when it is bound into a EXE or DLL file. Structure members are WORD
/// aligned and the last member of the structure is the ID instead of
/// the imageoffset.

type
PMEMICONDIRENTRY = ^TMEMICONDIRENTRY;
TMEMICONDIRENTRY = packed record
bWidth: BYTE; /// Width of the image
bHeight: BYTE; /// Height of the image (times 2)
bColorCount: BYTE; /// Number of colors in image (0 if >=8bpp)
bReserved: BYTE; /// Reserved
wPlanes: WORD; /// Color Planes
wBitCount: WORD; /// Bits per pixel
dwBytesInRes: DWORD; /// how many bytes in this resource?
nID: WORD; /// the ID
end;

type
PMEMICONDIR = ^TMEMICONDIR;
TMEMICONDIR = packed record
idReserved: WORD; /// Reserved
idType: WORD; /// resource type (1 for icons)
idCount: WORD; /// how many images?
idEntries: array[0..10] of TMEMICONDIRENTRY; /// the entries for each image
///查看msdn,这个数组长度应该是1,但是为什么图标猎手定义的是0..10?
end;

/// These next two structs represent how the icon information is stored
/// in an ICO file.

type
PICONDIRENTRY = ^TICONDIRENTRY;
TICONDIRENTRY = packed record
bWidth: BYTE; /// Width of the image
bHeight: BYTE; /// Height of the image (times 2)
bColorCount: BYTE; /// Number of colors in image (0 if >=8bpp)
bReserved: BYTE; /// Reserved
wPlanes: WORD; /// Color Planes
wBitCount: WORD; /// Bits per pixel
dwBytesInRes: DWORD; /// how many bytes in this resource?
dwImageOffset: DWORD; /// where in the file is this image
end;

type
PICONDIR = ^TICONDIR;
TICONDIR = packed record
idReserved: WORD; /// Reserved
idType: WORD; /// resource type (1 for icons)
idCount: WORD; /// how many images?
idEntries: array[0..0] of TICONDIRENTRY; /// the entries for each image
end;

/// The following two structs are for the use of this program in
/// manipulating icons. They are more closely tied to the operation
/// of this program than the structures listed above. One of the
/// main differences is that they provide a pointer to the DIB
/// information of the masks.
type
PICONIMAGE = ^TICONIMAGE;
TICONIMAGE = packed record
Width, Height, Colors: UINT; /// Width, Height and bpp
lpBits: pointer; /// ptr to DIB bits
dwNumBytes: DWORD; /// how many bytes?
pBmpInfo: PBitmapInfo;
end;
{ ///这是原来的,上面的是对照IconHunt的
TICONIMAGE = packed record
Width, Height, Colors: UINT; /// Width, Height and bpp
lpBits: pointer; /// ptr to DIB bits
dwNumBytes: DWORD; /// how many bytes?
lpbi: PBITMAPINFO; /// ptr to header
lpXOR: LPBYTE; /// ptr to XOR image bits
lpAND: LPBYTE; /// ptr to AND image bits
end;
}
type
PICONRESOURCE = ^TICONRESOURCE;
TICONRESOURCE = packed record
nNumImages: UINT; /// How many images?
IconImages: array[0..10] of TICONIMAGE; /// Image entries
end;
{///下面是原来的,上面是对照IconHunt的
TICONRESOURCE = packed record
bHasChanged: BOOL; /// Has image changed?
szOriginalICOFileName: array[0..MAX_PATH] of char; /// Original name
szOriginalDLLFileName: array[0..MAX_PATH] of char; /// Original name
nNumImages: UINT; /// How many images?
IconImages: array[0..0] of ICONIMAGE; /// Image entries
end;
}

type
TPageInfo = packed record
Width: byte;
Height: byte;
ColorQuantity: integer;
Reserved: DWORD;
PageSize: DWORD;
PageOffSet: DWORD;
end;

type
TPageDataHeader = packed record
PageHeadSize: DWORD;
XSize: DWORD;
YSize: DWORD;
SpeDataPerPixSize: integer;
ColorDataPerPixSize: integer;
Reserved: DWORD;
DataAreaSize: DWORD;
ReservedArray: array[0..15] of char;
end;

type
TIcoFileHeader = packed record
FileFlag: array[0..3] of byte;
PageQuartity: integer;
PageInfo: TPageInfo;
end;

///function WriteIconToFile(Bitmap: hBitmap; Icon: hIcon; szFileName: string): Boolean; overload;
function ExtractIconFromFile(ResFileName: string; IcoFileName: string; nIndex: string): Boolean;
function WriteIconResourceToFile(hFile: hwnd; lpIR: PICONRESOURCE): Boolean;

implementation

function WriteICOHeader(hFile: HWND; nNumEntries: UINT): Boolean;
type
TFIcoHeader = record
wReserved: WORD;
wType: WORD;
wNumEntries: WORD;
end;
var
IcoHeader: TFIcoHeader;
/// Output: WORD;
dwBytesWritten: DWORD;
begin
Result := False;
IcoHeader.wReserved := 0;
IcoHeader.wType := 1;
IcoHeader.wNumEntries := WORD(nNumEntries);
if not WriteFile(hFile, IcoHeader, SizeOf(IcoHeader), dwBytesWritten, nil) then
begin
MessageBox(0, pchar(SysErrorMessage(GetLastError)), 'info', MB_OK);
exit;
end;
if dwBytesWritten <> SizeOf(IcoHeader) then
exit;
{
Output := 0;
/// Write 'reserved' WORD
if not WriteFile(hFile, Output, SizeOf(WORD), dwBytesWritten, nil) then
exit;
/// Did we write a WORD?
if dwBytesWritten <> SizeOf(WORD) then exit;
/// Write 'type' WORD (1)
Output := 1;
if not WriteFile(hFile, Output, SizeOf(WORD), dwBytesWritten, nil) then
exit;
if dwBytesWritten <> SizeOf(WORD) then exit;
/// Write Number of Entries
Output := WORD(nNumEntries);
if not WriteFile(hFile, Output, SizeOf(WORD), dwBytesWritten, nil) then
exit;
if dwBytesWritten <> SizeOf(WORD) then exit;
}
Result := True;
end;

function CalculateImageOffset(lpIR: PICONRESOURCE; nIndex: UINT): DWORD;
var
dwSize: DWORD;
i: integer;
begin
/// Calculate the ICO header size
dwSize := 3 * sizeof(WORD);
/// Add the ICONDIRENTRY's
inc(dwSize, lpIR.nNumImages * sizeof(TICONDIRENTRY));
/// Add the sizes of the previous images
for i := 0 to nIndex - 1 do
inc(dwSize, lpIR.IconImages.dwNumBytes);
/// we're there - return the number
Result := dwSize;
end;

function WriteIconResourceToFile(hFile: hwnd; lpIR: PICONRESOURCE): Boolean;
var
i: UINT;
dwBytesWritten: DWORD;
ide: TICONDIRENTRY;
dwTemp: DWORD;
begin
/// open the file
Result := False;
/// Write the ICONDIRENTRY's
for i := 0 to lpIR^.nNumImages - 1 do
begin
/// Convert internal format to ICONDIRENTRY
ide.bWidth := lpIR^.IconImages.Width;
ide.bHeight := lpIR^.IconImages.Height;
ide.bReserved := 0;
ide.wPlanes := lpIR^.IconImages.pBmpInfo.bmiHeader.biPlanes;
ide.wBitCount := lpIR^.IconImages.pBmpInfo.bmiHeader.biBitCount;
if ide.wPlanes * ide.wBitCount >= 8 then
ide.bColorCount := 0
else
ide.bColorCount := 1 shl (ide.wPlanes * ide.wBitCount);
ide.dwBytesInRes := lpIR^.IconImages.dwNumBytes;
ide.dwImageOffset := CalculateImageOffset(lpIR, i);
/// Write the ICONDIRENTRY out to disk
if not WriteFile(hFile, ide, sizeof(TICONDIRENTRY), dwBytesWritten, nil) then
exit;
/// Did we write a full ICONDIRENTRY ?
if dwBytesWritten <> sizeof(TICONDIRENTRY) then
exit;
end;
/// Write the image bits for each image
for i := 0 to lpIR^.nNumImages - 1 do
begin
dwTemp := lpIR^.IconImages.pBmpInfo^.bmiHeader.biSizeImage;
/// Set the sizeimage member to zero
lpIR^.IconImages.pBmpInfo^.bmiHeader.biSizeImage := 0;
/// Write the image bits to file
if not WriteFile(hFile, lpIR^.IconImages.lpBits^, lpIR^.IconImages.dwNumBytes, dwBytesWritten, nil) then
exit;
if dwBytesWritten <> lpIR^.IconImages.dwNumBytes then
exit;
/// set it back
lpIR^.IconImages.pBmpInfo^.bmiHeader.biSizeImage := dwTemp;
end;
Result := True;
end;

function AWriteIconToFile(bitmap: hBitmap; Icon: hIcon; szFileName: string): Boolean;
var
fh: file of byte;
IconInfo: _ICONINFO;
PageInfo: TPageInfo;
PageDataHeader: TPageDataHeader;
IcoFileHeader: TIcoFileHeader;
BitsInfo: tagBITMAPINFO;
p: pointer;
PageDataSize: integer;
begin
Result := False;
GetIconInfo(Icon, IconInfo);
AssignFile(fh, szFileName);
FileMode := 1;
Reset(fh);

GetDIBits(0, Icon, 0, 32, nil, BitsInfo, DIB_PAL_COLORS);
GetDIBits(0, Icon, 0, 32, p, BitsInfo, DIB_PAL_COLORS);
PageDataSize := SizeOf(PageDataHeader) + BitsInfo.bmiHeader.biBitCount;

PageInfo.Width := 32;
PageInfo.Height := 32;
PageInfo.ColorQuantity := 65535;
Pageinfo.Reserved := 0;
PageInfo.PageSize := PageDataSize;
PageInfo.PageOffSet := SizeOf(IcoFileHeader);

IcoFileHeader.FileFlag[0] := 0;
IcoFileHeader.FileFlag[1] := 0;
IcoFileHeader.FileFlag[2] := 1;
IcoFileHeader.FileFlag[3] := 0;
IcoFileHeader.PageQuartity := 1;
IcoFileHeader.PageInfo := PageInfo;

FillChar(PageDataHeader, SizeOf(PageDataHeader), 0);
PageDataHeader.XSize := 32;
PageDataHeader.YSize := 32;
PageDataHeader.SpeDataPerPixSize := 0;
PageDataHeader.ColorDataPerPixSize := 32;
PageDataHeader.PageHeadSize := SizeOf(PageDataHeader);
PageDataHeader.Reserved := 0;
PageDataHeader.DataAreaSize := BitsInfo.bmiHeader.biBitCount;

BlockWrite(fh, IcoFileHeader, SizeOf(IcoFileHeader));
BlockWrite(fh, PageDataHeader, SizeOf(PageDataHeader));
BlockWrite(fh, p, BitsInfo.bmiHeader.biBitCount);
CloseFile(fh);
end;

function AdjustIconImagePointers(lpImage: PICONIMAGE): Bool;
begin
if lpImage = nil then
begin
Result := False;
exit;
end;
lpImage.pBmpInfo := PBitMapInfo(lpImage^.lpBits);
lpImage.Width := lpImage^.pBmpInfo^.bmiHeader.biWidth;
lpImage.Height := (lpImage^.pBmpInfo^.bmiHeader.biHeight) div 2;
lpImage.Colors := lpImage^.pBmpInfo^.bmiHeader.biPlanes * lpImage^.pBmpInfo^.bmiHeader.biBitCount;
Result := true;
end;

function ExtractIconFromFile(ResFileName: string; IcoFileName: string; nIndex: string): Boolean;
var
h: HMODULE;
lpMemIcon: PMEMICONDIR;
lpIR: TICONRESOURCE;
src: HRSRC;
Global: HGLOBAL;
i: integer;
hFile: hwnd;
begin
Result := False;
hFile := CreateFile(pchar(IcoFileName), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if hFile = INVALID_HANDLE_VALUE then exit; ///Error Create File
h := LoadLibraryEx(pchar(ResFileName), 0, LOAD_LIBRARY_AS_DATAFILE);
if h = 0 then exit;
try
src := FindResource(h, pchar(nIndex), RT_GROUP_ICON);
if src = 0 then
Src := FindResource(h, Pointer(StrToInt(nIndex)), RT_GROUP_ICON);
if src <> 0 then
begin
Global := LoadResource(h, src);
if Global <> 0 then
begin
lpMemIcon := LockResource(Global);
if Global <> 0 then
begin
/// lpIR := @IR;
try
lpIR.nNumImages := lpMemIcon.idCount;
/// Write the header
for i := 0 to lpMemIcon^.idCount - 1 do
begin
src := FindResource(h, MakeIntResource(lpMemIcon^.idEntries.nID), RT_ICON);
if src <> 0 then
begin
Global := LoadResource(h, src);
if Global <> 0 then
begin
lpIR.IconImages.dwNumBytes := SizeofResource(h, src);
GetMem(lpIR.IconImages.lpBits, lpIR.IconImages.dwNumBytes);
CopyMemory(lpIR.IconImages.lpBits, LockResource(Global), lpIR.IconImages.dwNumBytes);
if not AdjustIconImagePointers(@(lpIR.IconImages)) then exit;
end;
end;
end;
if WriteICOHeader(hFile, lpIR.nNumImages) then ///No Error Write File
if WriteIconResourceToFile(hFile, @lpIR) then
Result := True;
finally
for i := 0 to lpIR.nNumImages - 1 do
if assigned(lpIR.IconImages.lpBits) then
FreeMem(lpIR.IconImages.lpBits);
end;
end;
end;
end;
finally
FreeLibrary(h);
end;
CloseHandle(hFile);
end;

end.
 
谢谢Kingron了,我可要看很久了。
 
抓取資源中的圖標誰不知道﹐Delphi中就有例子。
關鍵是要知道圖標的文件格式﹐這樣才能把抓取
的圖標保存起來﹐順便說一句﹐強制地(簡單地)
將其保存成.ico文件是不行的﹐這不算是真正的圖
標文件﹐在Delphi的ImageList中就不能用。
 
用image的颜色是65536颜色,当时使用gifimage就编程难看得256颜色了,为什么,怎么避免
 
上边那个真的可以吗??
 
这个问题也折磨了我很长时间了
 
从文件中提取图标

首先声明一个API:
Function SHChangeIconDialog(hOwner:hwnd;szFilename:pchar;Reserved:longint; var lpIconIndex:Longint):Longint;stdcall;external 'shell32' index 62;


function TForm1.GetIconFromExe(ExeName:string):HIcon;
Var ic:longint;
idx:integer;
Exe:Pchar;
begin
getmem(Exe,255);
Exe:=pchar(ExeName); //参数可以为空串,看看结果是什么?
ic:=SHChangeIconDialog(handle,Exe,0,idx);
if ic<>0 then //成功调用
result:=extracticon(0,Exe,idx);
end;

这样使用:
imgicon.Picture.Icon.Handle:=GetIconFromExe('xxx.exe');

///////////////////////////////////////////////////////////////////////////
type ThIconArray = array[0..0] of hIcon;
type PhIconArray = ^ThIconArray;

function ExtractIconExA(lpszFile: PAnsiChar;
nIconIndex: Integer;
phiconLarge : PhIconArray;
phiconSmall: PhIconArray;
nIcons: UINT): UINT; stdcall;
external 'shell32.dll' name 'ExtractIconExA';


function ExtractIconExW(lpszFile: PWideChar;
nIconIndex: Integer;
phiconLarge: PhIconArray;
phiconSmall: PhIconArray;
nIcons: UINT): UINT; stdcall;
external 'shell32.dll' name 'ExtractIconExW';

function ExtractIconEx(lpszFile: PAnsiChar;
nIconIndex: Integer;
phiconLarge : PhIconArray;
phiconSmall: PhIconArray;
nIcons: UINT): UINT; stdcall;
external 'shell32.dll' name 'ExtractIconExA';


procedure TForm1.Button1Click(Sender: TObject);
var
NumIcons : integer;
pTheLargeIcons : phIconArray;
pTheSmallIcons : phIconArray;
LargeIconWidth : integer;
SmallIconWidth : integer;
SmallIconHeight : integer;
i : integer;
TheIcon : TIcon;
TheBitmap : TBitmap;
begin
NumIcons :=
ExtractIconEx('C:/Program Files/Borland/Delphi 3/BIN/delphi32.exe',
-1,
nil,
nil,
0);
if NumIcons > 0 then begin
LargeIconWidth := GetSystemMetrics(SM_CXICON);
SmallIconWidth := GetSystemMetrics(SM_CXSMICON);
SmallIconHeight := GetSystemMetrics(SM_CYSMICON);
GetMem(pTheLargeIcons, NumIcons * sizeof(hIcon));
GetMem(pTheSmallIcons, NumIcons * sizeof(hIcon));
FillChar(pTheLargeIcons^, NumIcons * sizeof(hIcon), #0);
FillChar(pTheSmallIcons^, NumIcons * sizeof(hIcon), #0);
ExtractIconEx('C:/Program Files/Borland/Delphi 3/BIN/delphi32.exe',
0,
pTheLargeIcons,
pTheSmallIcons,
numIcons);
{$IFOPT R+}
{$DEFINE CKRANGE}
{$R-}
{$ENDIF}
for i := 0 to (NumIcons - 1) do begin
DrawIcon(Form1.Canvas.Handle,
i * LargeIconWidth,
0,
pTheLargeIcons^);
TheIcon := TIcon. Create;
TheBitmap := TBitmap.Create;
TheIcon.Handle := pTheSmallIcons^;
TheBitmap.Width := TheIcon.Width;
TheBitmap.Height := TheIcon.Height;
TheBitmap.Canvas.Draw(0, 0, TheIcon);
TheIcon.Free;
Form1.Canvas.StretchDraw(Rect(i * SmallIconWidth,
100,
(i + 1) * SmallIconWidth,
100 + SmallIconHeight),
TheBitmap);
TheBitmap.Free;
end;
{$IFDEF CKRANGE}
{$UNDEF CKRANGE}
{$R+}
{$ENDIF}
FreeMem(pTheLargeIcons, NumIcons * sizeof(hIcon));
FreeMem(pTheSmallIcons, NumIcons * sizeof(hIcon));
end;
end;

end.
//////////////////////////////////////////////////////
var
TheIcon: TIcon;
begin
TheIcon := TIcon.Create;
TheIcon.Handle := ExtractIcon(hInstance,
'C:/SOMEPATH/SOMEPROG.EXE',
0);
{Do something with the icon}
TheIcon.Free;
end;

 
icons in win32

 

john hornick
microsoft corporation

created: september 29, 1995

download the iconpro sample.

abstract
this article describes, in detail, the format and use of icons in 32-bit windows. the following topics are covered; the format of icon resources in ico, dll and exe files, the format of icon images in memory, windows' use of icons, windows' selection of an icon image from an icon resource, and the apis provided to manipulate icon images. to follow the discussion, the reader should be familiar with device independent bitmaps (dibs) and their format. for more information about dibs, please refer to the following sources:

win32 sdk on-line help for the bitmapinfo structure
knowledge base article q81498 sample: dibs and their uses
knowledge base article q94326 sample: 16 and 32 bits-per-pel bitmap formats
sample code dealing with some of the topics in this article is available in the win32 sdk sample tree in the iconpro project.

disclaimer internal details discussed in this article are subject to change without notice in future versions of windows.

introduction
icons are a varied lot--they come in many sizes and color depths. a single icon resource--an ico file, or an icon resource in an exe or dll file--can contain multiple icon images, each with a different size and/or color depth. windows 95 and future versions of windows nt (collectively referred to as "windows" from here on) extract the appropriate size/color depth image from the resource depending on the context of the icon's use. windows also provides a collection of apis for accessing and displaying icons and icon images.

what's in an icon?
an icon resource can contain multiple icon images. for example, one icon resource--in this case, a single .ico file--can contain images in several sizes and color depths:

the ico file
an icon file, which usually has the ico extension, contains one icon resource. given that an icon resource can contain multiple images, it is no surprise that the file begins with an icon directory:

typedef struct
{
word idreserved; // reserved (must be 0)
word idtype; // resource type (1 for icons)
word idcount; // how many images?
icondirentry identries[1]; // an entry for each image (idcount of 'em)
} icondir, *lpicondir;

the idcount member indicates how many images are present in the icon resource. the size of the identries array is determined by idcount. there exists one icondirentry for each icon image in the file, providing details about its location in the file, size and color depth. the icondirentry structure is defined as:

typedef struct
{
byte bwidth; // width, in pixels, of the image
byte bheight; // height, in pixels, of the image
byte bcolorcount; // number of colors in image (0 if >=8bpp)
byte breserved; // reserved ( must be 0)
word wplanes; // color planes
word wbitcount; // bits per pixel
dword dwbytesinres; // how many bytes in this resource?
dword dwimageoffset; // where in the file is this image?
} icondirentry, *lpicondirentry;

for each icondirentry, the file contains an icon image. the dwbytesinres member indicates the size of the image data. this image data can be found dwimageoffset bytes from the beginning of the file, and is stored in the following format:

typdef struct
{
bitmapinfoheader icheader; // dib header
rgbquad iccolors[1]; // color table
byte icxor[1]; // dib bits for xor mask
byte icand[1]; // dib bits for and mask
} iconimage, *lpiconimage;

the icheader member has the form of a dib bitmapinfoheader. only the following members are used: bisize, biwidth, biheight, biplanes, bibitcount, bisizeimage. all other members must be 0. the biheight member specifies the combined height of the xor and and masks. the members of icheader define the contents and sizes of the other elements of the iconimage structure in the same way that the bitmapinfoheader structure defines a cf_dib format dib.

the iccolors member is an array of rgbquads. the number of elements in this array is determined by examining the icheader member.

the icxor member contains the dib bits for the xor mask of the image. the number of bytes in this array is determined by examining the icheader member. the xor mask is the color portion of the image and is applied to the destination using the xor operation after the application of the and mask.

the icand member contains the bits for the monochrome and mask. the number of bytes in this array is determined by examining the icheader member, and assuming 1bpp. the dimensions of this bitmap must be the same as the dimensions of the xor mask. the and mask is applied to the destination using the and operation, to preserve or remove destination pixels before applying the xor mask.

note the biheight member of the icheader structure represents the combined height of the xor and and masks. remember to divide this number by two before using it to perform calculations for either of the xor or and masks. also remember that the and mask is a monochrome dib, with a color depth of 1 bpp.

the following is an incomplete code fragment for reading an .ico file:

// we need an icondir to hold the data
picondir = malloc( sizeof( icondir ) );
// read the reserved word
readfile( hfile, &amp;(picondir->idreserved), sizeof( word ), &amp;dwbytesread, null );
// read the type word - make sure it is 1 for icons
readfile( hfile, &amp;(picondir->idtype), sizeof( word ), &amp;dwbytesread, null );
// read the count - how many images in this file?
readfile( hfile, &amp;(picondir->idcount), sizeof( word ), &amp;dwbytesread, null );
// reallocate icondir so that identries has enough room for idcount elements
picondir = realloc( picondir, ( sizeof( word ) * 3 ) +
( sizeof( icondirentry ) * picondir->idcount ) );
// read the icondirentry elements
readfile( hfile, picondir->identries, picondir->idcount * sizeof(icondirentry),
&amp;dwbytesread, null );
// loop through and read in each image
for(i=0;i<picondir->idcount;i++)
{
// allocate memory to hold the image
piconimage = malloc( picondir->identries.dwbytesinres );
// seek to the location in the file that has the image
setfilepointer( hfile, picondir->identries.dwimageoffset,
null, file_begin );
// read the image data
readfile( hfile, piconimage, picondir->identries.dwbytesinres,
&amp;dwbytesread, null );
// here, piconimage is an iconimage structure. party on it :)
// then, free the associated memory
free( piconimage );
}
// clean up the icondir memory
free( picondir );

complete code can be found in the icons.c module of iconpro, in a function named readiconfromicofile().

dll and exe files
icons can also be stored in .dll and .exe files. the structures used to store icon images in .exe and .dll files differ only slightly from those used in .ico files.

analogous to the icondir data in the ico file is the rt_group_icon resource. in fact, one rt_group_icon resource is created for each ico file bound to the exe or dll with the resource compiler/linker. the rt_group_icon resource is simply a grpicondir structure:

// #pragmas are used here to insure that the structure's
// packing in memory matches the packing of the exe or dll.
#pragma pack( push )
#pragma pack( 2 )
typedef struct
{
word idreserved; // reserved (must be 0)
word idtype; // resource type (1 for icons)
word idcount; // how many images?
grpicondirentry identries[1]; // the entries for each image
} grpicondir, *lpgrpicondir;
#pragma pack( pop )

the idcount member indicates how many images are present in the icon resource. the size of the identries array is determined by idcount. there exists one grpicondirentry for each icon image in the resource, providing details about its size and color depth. the grpicondirentry structure is defined as:

#pragma pack( push )
#pragma pack( 2 )
typedef struct
{
byte bwidth; // width, in pixels, of the image
byte bheight; // height, in pixels, of the image
byte bcolorcount; // number of colors in image (0 if >=8bpp)
byte breserved; // reserved
word wplanes; // color planes
word wbitcount; // bits per pixel
dword dwbytesinres; // how many bytes in this resource?
word nid; // the id
} grpicondirentry, *lpgrpicondirentry;
#pragma pack( pop )

the dwbytesinres member indicates the total size of the rt_icon resource referenced by the nid member. nid is the rt_icon identifier that can be passed to findresource(), loadresource() and lockresource() to obtain a pointer to the iconimage structure (defined above) for this image.

the following is an incomplete code fragment for reading icons from a .dll or .exe file:

// load the dll/exe without executing its code
hlib = loadlibraryex( szfilename, null, load_library_as_datafile );
// find the group resource which lists its images
hrsrc = findresource( hlib, makeintresource( nid ), rt_group_icon );
// load and lock to get a pointer to a grpicondir
hglobal = loadresource( hlib, hrsrc );
lpgrpicondir = lockresource( hglobal );
// using an id from the group, find, load and lock the rt_icon
hrsrc = findresource( hlib, makeintresource( lpgrpicondir->identries[0].nid ),
rt_icon );
hglobal = loadresource( hlib, hrsrc );
lpiconimage = lockresource( hglobal );
// here, lpiconimage points to an iconimage structure

complete code can be found in the icons.c module of iconpro, in a function named readiconfromexefile().

in memory
when dealing with icon resources in memory, the format is identical to the format used in .exe and .dll files. apis such as createiconfromresource() expect to be passed an iconimage structure. this is very convenient since findresource(), loadresource() and lockresource() can be used to load the rt_icon resource in that format.

an hicon handle is a handle to a single icon image, or rt_icon resource. in previous versions of windows, the size of an hicon image could be determined by calling getsystemmetrics() with the sm_cyicon and sm_cxicon flags. it is now possible, however, to have hicon handles for icons with non-standard sizes. hicon icons always have the same color format as the display device. see the discussion of apis below for more details on how to handle icons of different sizes and color depths using hicon handles.

when in windows
in windows, the system maintains the concept of two sizes of icons, small and large. further, the shell also has a concept of small and large icons. this means that in total, windows is aware of four different icon sizes--system small, system large, shell small, and shell large.

the system small size is derived from the size of window captions. the caption size can be adjusted from the "appearance" tab in the display properties dialog. adjustments made to the caption size are immediately reflected in the system small icon size. the system small size can be queried by calling getsystemmetrics() with the sm_cxsmicon and sm_cysmicon parameters.

the system large size is defined by the video driver and therefore cannot be changed dynamically. the system large size can be queried by calling getsystemmetrics() with the sm_cxicon and sm_cyicon parameters.

the shell small size is defined by windows, and currently windows does not support changing this value, nor is there currently a direct way to query this value.

the shell large size is stored in the registry under the following key:

hkey_current_user/control panel/desktop/windowmetrics/shell icon size

the shell large size can be changed by modifying the registry or from the "appearance" tab in the display properties dialog, which allows values from 16 to 72. following is an example of code that can be used to change the shell large icon size by accessing the registry:

dword setshelllargeiconsize( dword dwnewsize )
{
#define max_length 512
dword dwoldsize, dwlength = max_length, dwtype = reg_sz;
tchar szbuffer[max_length];
hkey hkey;

// get the key
regopenkey( hkey_current_user, "control panel//desktop//windowmetrics", &amp;hkey);
// save the last size
regqueryvalueex( hkey, "shell icon size", null, &amp;dwtype, szbuffer,
&amp;dwlength );
dwoldsize = atol( szbuffer );
// we will allow only values >=16 and <=72
if( (dwnewsize>=16) || (dwnewsize<=72) )
{
wsprintf( szbuffer, "%d", dwnewsize );
regsetvalueex( hkey, "shell icon size", 0, reg_sz, szbuffer,
lstrlen(szbuffer) + 1 );
}
// clean up
regclosekey( hkey );
// let everyone know that things changed
sendmessage( hwnd_broadcast, wm_settingchange, spi_seticonmetrics,
(lparam)("windowmetrics") );
return dwoldsize;
#undef max_length
}

table 1. where windows uses different sized icons
location icon size
 
desktop shell large
 
titlebar of windows system small
 
<alt><tab> dialog system large
 
start menu shell small / shell large

while windows imposes no restrictions on the sizes of icons, common sizes include 16, 32, and 48 pixels square. for this reason, developers are encouraged to include a minimum of the following sizes and color depths in their icon resources:

16 x 16 16 colors
 
32 x 32 16 colors
 
48 x 48 256 colors

choosing an icon
when windows prepares to display an icon, a desktop shortcut for example, it must parse the .exe or .dll file and extract the appropriate icon image. this selection is a two step process starting with the selection of the appropriate rt_group_icon resource, and ending with the selection of the proper rt_icon image from that rt_group_icon.

which icon?
if an .exe or .dll file has only one rt_group_icon resource, the first step is trivial; windows simply uses that resource. however, if more than one such group resource exists in the file, windows must decide which one to use. windows nt simply chooses the first resource listed in the application's rc script. on the other hand, windows 95's algorithm is to choose the alphabetically first named group icon if one exists. if one such group resource does not exist, windows chooses the icon with the numerically lowest identifier. so, to be sure that a particular icon is used for an application, the developer should insure that both of the following criteria are met:

the icon is placed before all other icons in the rc file.
if the icon is named, its name is alphabetically before any other named icon, otherwise its resource identifier is numerically smaller than any other icon.
which image?
once an rt_group_icon is chosen, the individual icon image, or rt_icon resource, must be selected and extracted. again, if there exists only one rt_icon resource for the group in question, the choice is trivial. however, if multiple images are present in the group, the following selection rules are applied:

the image closest in size to the requested size is chosen.
if two or more images of that size are present, the one that matches the color depth of the display is chosen.
if none exactly match the color depth of the display, windows chooses the image with the greatest color depth without exceeding the color depth of the display.
if all the size-matched images exceed the color depth of the display, the one with the lowest color depth is chosen.
windows treats all color depths of 8 or more bpp as equal. for example, it is pointless to have a 16x16 256 color image and a 16x16 16bpp image in the same resource--windows will simply choose the first one it encounters.
when the display is in 8bpp mode, windows will prefer a 16 color icon over a 256 color icon, and will display all icons using the system default palette.
apis
when dealing with icons, the developer can choose to manipulate the raw resource bytes, or let windows handle the low level details and simply use hicon handles. the advantage of handling the raw resource bytes is a gain in control, while the advantage of using the hicon handles is that of simplicity. for most purposes, the hicon interface is sufficient--it is likely that handling the raw resource bytes will be necessary only in the development of an icon handling program.

raw resource bytes
the standard windows api functions for manipulating resources--findresource(), loadresource() and lockresource()--can, of course, be used to handle icon resources.

enumresourcenames() can be used, passing in rt_group_icon, to find the available group icon resources. once the appropriate group resource is chosen, it can be loaded using findresource(), loadresource() and lockresource(). this will yield a pointer to a grpicondir structure.

the identries array is the searched for a match on the desired color depth and size. the nid member of that array element is then used as an argument to findresource(), passing in rt_icon. loadresource() and lockresource then yield a pointer to an iconimage structure for that icon image.

to allow windows to perform the color depth and size selection, the grpicondir structure can be passed to lookupiconidfromdirectory() or lookupiconidfromdirectoryex(). both of these functions return an id that can be used with rt_icon and findresource(), the latter providing a way to specify a desired size to match against.

the iconimage structure contains pointers to the dib bits for the masks. these pointers can be used in dib functions for direct manipulation. the iconimage structure is also conveniently suitable to be passed to createiconfromresource() or createiconfromresourceex() to yield an hicon handle. the former of the two functions creates an icon that is system large size. the latter provides a way to specify a desired size, and windows performs the appropriate conversions.

hicon handles
an hicon handle is a handle to a single icon image. this is analogous to a single rt_icon resource. the image is stored internally using device dependent bitmaps (ddbs). this implies that all hicon icons have the same color format as the display device. the size of the icon depends on its origin and the system defined icon sizes.

the available icon handling functions can be thought of in two groups--those that handle system large size icons and those that handle any size icons. the functions that handle only system large size icons are typically left over from 16 bit days, when the system defined only one icon size. the newer functions, those that handle any size icon, accept as a parameter the desired size of the icon.

one size fits all
the original icon handling functions were designed for a system that defined only one icon size. therefore, most of those functions are unaware of the possibility of more than one icon size and assume all icons are system large size.

loadicon(), extracticon() and drawicon() fall into this category. loadicon() and extracticon() always search for a match for system large size. if an exact match cannot be found, these two functions stretch the closest match to that size. they always return an icon of system large size. similarly, drawicon() always draws the icon at system large size. if a different size icon is passed to drawicon(), it is stretched and displayed at system large size.

createiconfromresource() also exhibits this behavior. it returns a handle to a system large size icon, stretching the rt_icon resource it was passed as necessary.

to each their own
now that windows has the ability to handle different sized icons, new api functions were added to handle them. in some cases, old functions were expanded and "ex" was added to their name. in other cases, whole new functions were added. the net result is that there is now full support for different sized icons in the windows api.

several different functions are available to get an hicon handle to a different sized icon. loadimage() can be used to extract an icon from an exe or dll file without the hassle of manually loading the resource bytes. createiconfromresourceex() is available if the resource bytes have been loaded.

createicon() and createiconindirect(), even though they have their roots in 16-bit land, do facilitate creating icons of different sizes. createicon() accept a desired width and height as parameters, while createiconindirect() creates an icon based on the bitmaps in the iconinfo parameter. note that both of these functions work with ddbs, not dibs.

shgetfileinfo() can also be used to get icons from files, providing the icon that the shell would display for the file. shgetfileinfo() works on any type of file, and can extract any of the four icons sizes, as shown below:

// load a system large icon image
shgetfileinfo( szfilename, 0, &amp;shfi, sizeof( shfileinfo ),
shgfi_icon | shgfi_largeicon);

// load a system small icon image
shgetfileinfo( szfilename, 0, &amp;shfi, sizeof( shfileinfo ),
shgfi_icon | shgfi_smallicon);

// load a shell large icon image
shgetfileinfo( szfilename, 0, &amp;shfi, sizeof( shfileinfo ),
shgfi_icon | shgfi_shelliconsize);

// load a shell small icon image
shgetfileinfo( szfilename, 0, &amp;shfi, sizeof( shfileinfo ),
shgfi_icon | shgfi_shelliconsize | shgfi_smallicon);

given an hicon handle, drawiconex() can be used to display it--at its normal size, at the system large size, or at any other size:

// draw it at its native size
drawiconex( hdc, nleft, ntop, hicon, 0, 0, 0, null, di_normal );

// draw it at the system large size
drawiconex( hdc, nleft, ntop, hicon, 0, 0, 0,
null, di_defaultsize | di_normal );

// draw it at some other size (40x40 in this example)
drawiconex( hdc, nleft, ntop, hicon, 40, 40, 0, null, di_normal );

note that drawiconex() will stretch the icon as necessary to make it fit the desired output size.

what's in there?
the win32 api provides a function for determining the characteristics of an icon, given its hicon handle. this function is geticoninfo(). geticoninfo() fills out an iconinfo structure with the information pertaining to the hicon. the iconinfo structure contains the following information:

typedef struct _iconinfo { // ii

bool ficon; // true for icon, false for cursor
dword xhotspot; // the x hotspot coordinate for cursor
dword yhotspot; // the y hotspot coordinate for cursor
hbitmap hbmmask; // handle to monochrome and mask bitmap
hbitmap hbmcolor; // handle to device dependent xor mask bitmap
} iconinfo;

given this information, an application can calculate the information needed to write the icon to a file. the and mask and xor mask dib bits can be obtained with calls to getdibits() on the two bitmaps in this structure.

a word on cursors
cursors, in win32, are very similar to icons. in fact, by changing only one line in the source code for iconpro, that sample can read .cur files. iconpro currently tests the idtype member of the icondir structure to make sure the file is an icon file. this check can be relaxed to allow the type for cursors (2) as well. also, hcursor handles can be used interchangeably with hicon handles in most win32 icon apis.

conclusion
although the icon specification has long been able to handle icons of odd sizes and color depths, only recently has windows responded with inherent support for such images. developers now have the option of dealing directly with the bits of an icon, or allowing windows to handle all the details. windows even provides api support for loading and displaying icons of non-standard sizes and different color depths.

&amp;copy; 1997 microsoft corporation. all rights reserved. legal notices

 
有人做出来了,你要吗?发给你
 
to lwsi:
I want,Please send to me,Thanks.
Boningsword@21cn.com
 
up[:D]

我也很关注这个问题,不是要混分的
 
谢谢!帮我大忙了。
 
后退
顶部