Many X applications nowadays provide nice coloured icons which are stored into the binary file directly. If the application follows the NET_WM specifications, then it is possible to retrieve the icon from the _NET_WM_ICON window property, if it is defined. Extracting the _NET_WM_ICON of an X application is therefore simply a matter of calling XGetWindowProperty with the correct arguments.
To demonstrate how this can be done in practice, I wrote a small program called xgeticon which let the user choose the window of a running X application and save the extracted icon into the file provided as argument. The program is inspired from xprop and uses the procedure explained here (dead) to retrieve and save the icon. The icon can be saved into any of the file formats supported by Imlib2; the format being automatically determined from the file extension.