2007-11-12

Extract Icons from resources in a DLL with GdiPlusX

This week calvin hsia came with a very interesting post, extract treeview or listview imagelist icons from a dll .

That calvin's post is dedicated to visual studio developers.

As in the comments there were some people asking the code for vfp, below i'm putting and adapted version for vfp users, using, of course, gdiplusx to help us extracting the icons from the resource.

 

There's still more to say about this, but in this first moment, i'm putting just the code to retrieve the embedded bitmap from the visual studio dll that calvin refers to. below is the most relevant part of the original code in vb .net from calvin, very easilly converted to vfp, using the gdiplusx library.

 



picture 1: relevant source code in vb .net

 

 

...and here is the vfp code. very simple, isn't it ?

 

Important
Requires vfp9 and gdiplusx to run. 
Please make sure that you have the latest version!
http://www.codeplex.com/vfpx/wiki/view.aspx?title=gdiplusx&referringtitle=home
* Init GdiPlusX
DO LOCFILE("System.app")

#DEFINE load_library_as_image_resource 0x20
#DEFINE load_library_as_datafile 2

DECLARE INTEGER LoadLibraryEx IN kernel32;
string lpfilename, INTEGER hmodule, INTEGER dwflags
DECLARE INTEGER LoadBitmap IN user32;
INTEGER hmodule, INTEGER hresinfo
DECLARE INTEGER FreeLibrary IN kernel32 long hmodule
DECLARE INTEGER DeleteObject IN win32api INTEGER hobject

LOCAL lhmodule, lhres, lcResFile

* lcResFile = ADDBS(GETENV("ProgramFiles")) + ;
"microsoft visual studio 9.0\common7\ide\msenv.dll"

lcResFile = ADDBS(GETENV("ProgramFiles")) + ;
"microsoft visual studio 10.0\common7\ide\msenv.dll"
IF NOT FILE(lcResFile)
lcResFile = GETFILE("dll")
ENDIF

lhModule = LoadLibraryEx(lcResFile, ;
0, load_library_as_image_resource + load_library_as_datafile)

lhRes = LoadBitmap(lhModule, 0x4f4)

IF lhRes > 0
LOCAL loBmp AS xfcBitmap
WITH _Screen.System.drawing
loBmp = .Bitmap.FromhBitmap(lhres)
loBmp.Save("c:\ResourceImage.bmp", .Imaging.ImageFormat.Bmp)
ENDWITH
ELSE
MESSAGEBOX("Could not load the file")
ENDIF

 

 

 



picture 2: the extracted image in the original size

 



picture 3: a part of the extracted image expanded 8 times

 

 

Cool ! but still not ready to be used in our vfp forms.

As that bitmap contains many icons in the same file, i'll use some gdi+ stuff to separate each of them, saving in a different file. we have to know the dimensions of each image, so i'll take the smallest value between the width and height, and use a loop to crop each icon image separately. the backgrounds also need to be treated, as i'll comment below.

For vs users, Calvin used a totally different technique to separate the images, using the listview and the treeview controls from VS. If someone could show me how to chieve this in vfp using his technique... it would be great !

 

Each image is saved in two different formats:

1 - bmp of 24 bits, with white background, to be used in vfp buttons. the white background is rgb(255,255,255). for safety purposes, i also changed all original whites from the icons to rgb(254,254,254). this way, vfp will not make these parts of the images as transparent.

2 - png of 32bits, with the background color set as transparent

 

There is some more complex code that i used to crop the images that I've never showed before in my blog. It's all full of comments, and I hope, it's easy to understand.

 
************************************************************************************************************
* program: extracticonsfromresource2.prg
* author : cesar c
*
* extracts all 16x16 icons stored in dlls
* extracts the icons from the big collection pictures obtained from the resource
* aplies effects to the image to keep transparencies
*
* sample totally based on calvin hsia's article from his blog
* "extract treeview or listview imagelist icons from a dll"
*
http://blogs.msdn.com/calvin_hsia/archive/2007/11/06/5948486.aspx?commentposted=true#commentmessage
*
* prerequisites:
* vfp9 and gdiplusx library -
http://www.codeplex.com/vfpx/wiki/view.aspx?title=gdiplusx&referringtitle=home
************************************************************************************************************

do locfile("system.app")

#define load_library_as_image_resource 0x20
#
define load_library_as_datafile 2

declare integer loadlibraryex in kernel32;
   string lpfilename,;
   integer hfile,;
   integer dwflags
declare long freelibrary in kernel32 long hmodule
declare integer loadbitmap in user32;
   integer hinstance,;
   integer lpbitmapname
declare integer deleteobject in win32api integer hobject

with _screen.system.drawing
   local lcfile, lcshortname, lciconfile
   local hmodule, hres
   local n, lnwidth, lnheight
   local loicon as xfcbitmap
   local lobmp as xfcbitmap
   local loborderclr as xfccolor

   * these objects will be used only if the output is bmp
   local locloned as xfcbitmap
   local locolormap as xfccolormap
   locolormap = .imaging.colormap.new()
   local loattr as xfcimageattributes
   m.loattr = .imaging.imageattributes.new()

   lcfile = "c:\program files\microsoft visual studio 9.0\common7\ide\msenv.dll" +
chr(0)
   lcshortname = "c:\" +
justfname(lcfile)
   hmodule = loadlibraryex(lcfile, 0, load_library_as_image_resource + load_library_as_datafile)
   hres = loadbitmap(hmodule, 0x4f4)


   if hres = 0
      loop
   endif


   lobmp = .bitmap.fromhbitmap(hres)
   lobmp.
save(lcshortname + "_allicons.png", .imaging.imageformat.png)
   deleteobject(hres)
   lnheight = lobmp.
height
   lnwidth = lnheight

   if lnheight > 16 && this is a big image, so it's not the icon we're interested in
      loop
   endif

   * get the quantity of bits per pixels of the image.
   * if we have an indexed format (< 24), we wont create the transparencies manually.
   local lnpixfmtsize
   lnpixfmtsize = lobmp.getpixelformatsize(lobmp.pixelformat)


   * get the top left pixel color, presuming this color will be converted
   * to transparent
   loborderclr = lobmp.getpixel(0,0)

   * make a copy of the bitmap for further processing as bmp
locloned = lobmp.clone()


   *-* beginning of the png cropping
   * save the icons as pngs with transparent background
   if lnpixfmtsize >= 24 && the background is not white, so
      lobmp.maketransparent(loborderclr)
   endif

   for n = 0 to (lobmp.width / lnwidth) - 1
      lciconfile = lcshortname + "_icon_" +
transform(n) + ".png"
      loicon = lobmp.clone(.rectangle.new(n * lnwidth, 0, lnwidth, lnheight))
      if vartype(loicon) = "o"
         loicon.
save(lciconfile, .imaging.imageformat.png)
      endif
   endfor


   * restore the original bitmap object for the bmp transformations
   lobmp = locloned.clone()
   *-* end of png cropping


   *-* beginning of the bmp cropping
   if loborderclr <> .color.white and ;
      lnpixfmtsize >= 24
&& the background is not white, so
            && let's make some changes to adapt the icon to have a white
            && background, that will appear transparent in buttons


      * convert original whites rgb(255,255,255) to off white - rgb(254,254,254)
      * this way, the whites will remain without the need of a mask
      locolormap.oldcolor = .color.white
      locolormap.newcolor = .
color.fromargb(255,254,254,254)
      loattr.setremaptable(locolormap)
      logfx = .graphics.fromimage(lobmp)
      lorect = lobmp.getbounds()
      logfx.drawimage(lobmp, m.lorect, m.lorect, .graphicsunit.
pixel, loattr)

      * next step, convert the borders to pure white, rgb(255,255,255) that will become transparent in buttons
      locolormap.oldcolor = loborderclr
      locolormap.newcolor = .
color.white
      loattr.setremaptable(locolormap)
      logfx.drawimage(lobmp, m.lorect, m.lorect, .graphicsunit.
pixel, loattr)
   endif

   * continue, cropping each icon from the big image
   for n = 0 to (lobmp.width / lnwidth) - 1
      lciconfile = lcshortname + "_icon_" +
transform(n) + ".bmp"
      loicon = lobmp.clone(.rectangle.new(n * lnwidth, 0, lnwidth, lnheight), .imaging.pixelformat.format24bpprgb)
      if vartype(loicon) = "o"
         loicon.
save(lciconfile, .imaging.imageformat.bmp)
      endif
   endfor
   *-* end of the bmp cropping

   freelibrary(hmodule)
endwith

 

 



picture 4: thumbnails of some of the images cropped and transformed from the resource file

 

 

but there's still one important problem that i wasn't able to solve yet: to list all available resources. so, for the case i wanted to extract the biggest quantity of available icons in all resource files of my computer, the provisory solution i've found was to create a loop, from 0 (zero) to 65535, trying to retrieve the image resource.

i've just based myself in another old post of mine, extract icons from exe, dll and ico files with gdiplusx , and created a new script for extracting all available 16x16 icons in all resources from a specific folder, checking also all the subdirectories. the final result is tons of icons, all stored in just one folder, "c:\resource icons", in two versions, one in png with the transparent background, and another version stored in the format of bmp of 24 bits, with white background, that is the format best supported by vfp for our command buttons.

when you run this last sample, depending on the folder that you choose, and the remaining subfolders, the resulting process may be really long, so i ask you to be patient, but i ensure you it's worth. when finished, open the folder "c:\resource icons". my search in drive c of my computer, resulted in more than 25000 different icons !

enjoy !
************************************************************************************************************
* program: extracticonsfromresource3.prg
* author : cesar ch
*
* extracts all 16x16 icons stored in dlls or exe files
* explores recursively in all the directory and subdirectories selected
* extracts the icons from the big collection pictures obtained from the resource
*
* sample totally based on calvin hsia's article from his blog
* "extract treeview or listview imagelist icons from a dll"
*
http://blogs.msdn.com/calvin_hsia/archive/2007/11/06/5948486.aspx?commentposted=true#commentmessage
*
* prerequisites:
* vfp9 and gdiplusx library -
http://www.codeplex.com/vfpx/wiki/view.aspx?title=gdiplusx&referringtitle=home
************************************************************************************************************

do locfile("system.app")

#define load_library_as_image_resource 0x20
#
define load_library_as_datafile 2

declare integer loadlibraryex in kernel32;
   string lpfilename,;
   integer hfile,;
   integer dwflags
declare long freelibrary in kernel32 long hmodule
declare integer loadbitmap in user32;
   integer hinstance,;
   integer lpbitmapname
declare integer deleteobject in win32api integer hobject

* create destination directory to receive the extracted icons
lcdir = "c:\resourceicons"
if not directory(lcdir)
   mkdir (lcdir)
endif

* create the cursor that will store the valid file locations
create cursor recursive (cfile c(250))
local lcselecteddir
lcselecteddir =
getdir()
if empty(lcselecteddir)
   wait window "invalid directory"
   return .f.
endif
wait window
"retrieving folders information" nowait

* scan through the selected and the subfolders
=recurse(lcselecteddir)

with _screen.system.drawing

local lcfile, lcshortname, lciconfile, lntotrec
local lnoldpercentage, lnpercentage
local hmodule, hres
local n, lnwidth, lnheight
local loicon as xfcbitmap
local lobmp as xfcbitmap
local loborderclr as xfccolor

* these objects will be used only if the output is bmp
local locloned as xfcbitmap
local locolormap as xfccolormap
locolormap = .imaging.colormap.new()
local loattr as xfcimageattributes
m.loattr = .imaging.imageattributes.new()

store 0 to lnpercentage, lnoldpercentage
lntotrec =
reccount()

scan
   lcfile = alltrim(recursive.cfile) + chr(0)
   lcshortname =
justfname(lcfile)
   hmodule = loadlibraryex(lcfile, 0, load_library_as_image_resource + load_library_as_datafile)
   for x = 0 to 0xffff
      hres = loadbitmap(hmodule, x)
&& 0x4f4)
      if hres = 0
         loop
      endif
      lcnewfile = addbs(lcdir) + lcshortname
      lobmp = .
bitmap.fromhbitmap(hres)
      lobmp.
save(lcnewfile + "_allicons_r" + transform(x) + ".png", .imaging.imageformat.png)
      deleteobject(hres)
      lnheight = lobmp.
height
      lnwidth = lnheight
      if lnheight > 16 && this is a big image, so it's not the icon we're interested in
         loop
      endif

      * get the quantity of bits per pixels of the image.
      * if we have an indexed format (< 24), we wont create the transparencies manually.
      local lnpixfmtsize
      lnpixfmtsize = lobmp.getpixelformatsize(lobmp.pixelformat)


      * get the top left pixel color, presuming this color will be converted
      * to transparent
      loborderclr = lobmp.getpixel(0,0)

      * make a copy of the bitmap for further processing as bmp
      locloned = lobmp.clone()



      *-* beginning of the png cropping
      * save the icons as pngs with transparent background
      if lnpixfmtsize >= 24 && the background is not white, so
         lobmp.maketransparent(loborderclr)
      endif

      for n = 0 to (lobmp.width / lnwidth) - 1
          lciconfile = lcnewfile +
transform(x) + "_icon_" + transform (n) + ".png"
          loicon = lobmp.clone(.rectangle.new(n * lnwidth, 0, lnwidth, lnheight))
          if vartype(loicon) = "o"
             loicon.
save(lciconfile, .imaging.imageformat.png)
          endif
      endfor
      * restore the original bitmap object for the bmp transformations
      lobmp = locloned.clone()
      *-* end of png cropping

      *-* beginning of the bmp cropping
      if loborderclr <> .color.white and ;
         lnpixfmtsize >= 24
&& the background is not white, so
         && let's make some changes to adapt the icon to have a white
         && background, that will appear transparent in buttons
         * convert original whites rgb(255,255,255) to off white - rgb(254,254,254)
         * this way, the whites will remain without the need of a mask
         locolormap.oldcolor = .color.white
         locolormap.newcolor = .
color.fromargb(255,254,254,254)
         loattr.setremaptable(locolormap)
         logfx = .graphics.fromimage(lobmp)


         lorect = lobmp.getbounds()
         logfx.drawimage(lobmp, m.lorect, m.lorect, .graphicsunit.pixel, loattr)

         * next step, convert the borders to pure white, rgb(255,255,255) that will become transparent in buttons
         locolormap.oldcolor = loborderclr
         locolormap.newcolor = .
color.white
         loattr.setremaptable(locolormap)
         logfx.drawimage(lobmp, m.lorect, m.lorect, .graphicsunit.
pixel, loattr)
      endif

      * continue, cropping each icon from the big image
      for n = 0 to (lobmp.width / lnwidth) - 1
         lciconfile = lcnewfile +
transform(x) + "_icon_" + transform(n) + ".bmp"
         loicon = lobmp.clone(.rectangle.new(n * lnwidth, 0, lnwidth, lnheight), .imaging.pixelformat.format24bpprgb)
         if vartype(loicon) = "o"
            loicon.
save(lciconfile, .imaging.imageformat.bmp)
         endif
      endfor
      *-* end of the bmp cropping

   endfor

   freelibrary(hmodule)

   * show progression
   lnrec = recno()
   lnpercentage =
round((lnrec / lntotrec),2)
   if lnpercentage > lnoldpercentage
      wait window "extracting icons from files..." + chr(13) + ;
         "elapsed: " +
transform(lnpercentage * 100) + " %" nowait
      lnoldpercentage = lnpercentage
   endif
endscan
endwith
return


*****************************************************************************************
* function : recurse
* author : michael reynolds
* description : good for performing file processing throughout an entire directory tree.
* the function, recurse(), is called with the full path of a directory.
* recurse() will then read all files and directories in the path.
* a function can be called to process files that it finds.
* plus, the function calls itself to process any sub-directories.
*
http://fox.wikis.com/wc.dll?wiki~recursivedirectoryprocessing~vfp
*****************************************************************************************
function recurse(pcdir)
local lnptr, lnfilecount, lafilelist, lcdir, lcfile
chdir (pcdir)
dimension lafilelist[1]
*--- read the chosen directory.
lnfilecount = adir(lafilelist, '*.*', 'd')
for lnptr = 1 to lnfilecount

   if 'd' $ lafilelist[lnptr, 5]
      *--- get directory name.
      lcdir = lafilelist[lnptr, 1]
      *--- ignore current and parent directory pointers.
      if lcdir != '.' and lcdir != '..'
         *--- call this routine again.
         recurse(lcdir)
      endif
   else
      *--- get the file name.
      lcfile = lower(fullpath(lafilelist[lnptr, 1]))
      *--- insert into cursor if .exe, .ico or .dll
      if inlist(lower(justext(lcfile)),"dll","exe")
         insert into recursive (cfile) values (lcfile)
      endif
   endif
endfor
*--- move back to parent directory.
chdir ..
endfunc

 

4 comments:

  1. Cesar!

    What a wonderful piece of code! I'm sure I will be able to find some good uses for the capabilities you expose.

    Thank you!

    Malcolm
    Hi Marcolm.
    Kudos to Calvin. I've just brought the main idea to "our world". But I agree with you on the usability of this. I'm still making tests here, but for sure lots of cool things can be obtained just adapting the codes shown here.
    One point that I wanted to better emphasize is to show people that it is really easy to take advantage of the codes created by people from other languages, specially .NET and Visual Basic.
    Regards
    Cesar

    ReplyDelete
  2. Nice article. I wrote one that is related, maybe not a masterpiece like yours, but its my first time alone with the GDIPLUSX classes!

    http://www.ctl32.com.ar/articles/playing_with_gdiplusx.asp
    Hi Carlos,
    GREAT ARTICLE !
    My true inspiration for this article was a comment of yours that I found in Calvin's blog. The aproaches of the two articles are different. I've learned some cool things from it.
    BTW, I'll add a link to it to our GdiPlusX "articles" page in Codeplex.
    Regards
    Cesar

    ReplyDelete
  3. Main Object to extract VFP9 Icon for the Caption of Forms for Own .Exe when run above code error popup


    Cannot find Entry Point deleteobject in the DLL

    ReplyDelete
  4. Thanks !
    When this blog was moved to WordPress, all the Casing markups were lost. I fixed the relevant code from this post. In other posts, we can have the same issues,
    unfortunately.
    Regards

    ReplyDelete