Extracting Maya Icons

I am kicking myself for not bookmarking a page I came across that showed how to easily extract maya’s icons into individual files.
Anyone know how to do that?

Thanks.

1 Like

[QUOTE=rgkovach123;23036]I am kicking myself for not bookmarking a page I came across that showed how to easily extract maya’s icons into individual files.
Anyone know how to do that?

Thanks.[/QUOTE]

In older maya versions(pre-2011) there was a MayaRes.dll file which what you are probably thinking about, don’t really know about the newer versions tho.

UPDATE:

For saving out the factory icons:

from pymel.core import *
for item in resourceManager():
    resourceManager(saveAs=(item, "C:/stuff/{0}".format(item)))

I don’t know if the magnets(snapping) and other stuff are in it but you can save pixmaps from Qt items, if you need a code that grabs all the pixmaps from Qt items I will do it, but at least tomorrow since I got to go now.

2 Likes

that is it! thanks!


import maya.cmds as cmds
for item in cmds.resourceManager(nf='*png'):
    cmds.resourceManager(s=(item, "C:/temp/mayaicons/{0}".format(item)))

this dumped out all the icons!

you can also use those in your QT guis by setting the resource path to ‘:polyCube.png’, etc.

3 Likes

that is even better! thanks!

I just want to add a quick addendum to the code above as it wasn’t working for 2015 and there is no information really anywhere on how to extract these well.


from pymel.core import *
for item in resourceManager(nameFilter='*'):
    try:
        #Make sure the folder exists before attempting.
        resourceManager(saveAs=(item, "C:/temp/icons/{0}".format(item)))    
    except:
        #For the cases in which some files do not work for windows, name formatting wise. I'm looking at you 'http:'!
        print item

Before, without the nameFilter argument, calling to the resource manager with no argument would return none.

Update for Maya 2016.

I haven’t found a way to extract the high-resolution icons yet, I get the default icons authored for 100% displays.

Here is some information regarding authoring custom icons that work at different resolutions.

http://help.autodesk.com/view/MAYAUL/2016/ENU/?guid=GUID-F2900709-59D3-4E67-A217-4FECC84053BE

I made my own version, with a tad more error handling and slightly easier user-friendlyness.
Just edit the icon name and directory from the variables in full caps at the top.

from pymel.core import *
import os
import maya.api.OpenMaya as om
def main():
    ###### USER CUSTOMIZATION ######
    ICONS_ITEMS = "play_regularrrrr.png"
    OUTPUT_DIRECTORY = "C:/temp/icons/"
    # Don't forget the closing slash!
    ######   ######  ######   ######

############################################################################
    # Creates the folder if doesn't exist
    if not os.path.exists(OUTPUT_DIRECTORY):
        os.makedirs(OUTPUT_DIRECTORY)

    try:
        for item in resourceManager(nameFilter=ICONS_ITEMS):
            try:
                resourceManager(saveAs=(item, '{}{}'.format(OUTPUT_DIRECTORY,item)))
                print("Saved : {}".format(item))
            except:
                #For the cases in which some files do not work for windows, name formatting wise. I'm looking at you 'http:'!
                print("Couldn't save : {}".OUTPUT_DIRECTORY+item)

        om.MGlobal.displayInfo("Done saving icons. See script editor for more details")
    except:
        om.MGlobal.displayWarning("Couldn't find the icon. Check the 'ICON_ITEMS' variable content")

if __name__ == "__main__":
    main()

Also shared here:

Maybe a gui one day? x)

For some reason, almost everyone tries to extract Maya resource files with the pyMEL command resourceManager
Although this command is available unchanged in both MEL and Python since at least Maya 2011.
The use of PyMEL and OpenMaya, in this particular case, is not motivated or justified by anything.
And after recent events (when the very existence of PyMEL in Maya was in question and PyMEL was not available for Maya 2024 for a long time), PyMEL should be used with great care. Of course, sometimes you just don’t have a choice (Legassi/Pipeline, mGear, MSLiveLink/DHI, etc)

It is possible / necessary to create a full-fledged graphical interface for this operation, probably only for the purpose of self-education and expansion of consciousness :slight_smile:

Variant with use Maya Python (with detailed comments):

import os
importmaya.mel as mel
import maya.cmds as cmds
# Import "traceback.print_exc" for extended output of information about errors.
from traceback import print_exc as traceback_print_exc
# Import "time.perf_counter" or "time.clock" (depending on Python version)
# to measure the time spent executing code.
try:
    from time import perf_counter as t_clock
except ImportError:
    from time import clock as t_clock


# The "extract_maya_resource_files" function will extract to the "path" directory
# all Maya resource files whose names match the "name_filter" filter criteria.
# If such a directory does not exist, it will be created with all intermediate directories.
# If no filter argument is passed to the function, then,
# by default, all resource files will be retrieved.
def extract_maya_resource_files(path, name_filter = '*'):
    # Normalize the user-specified path.
    # To work correctly with paths on various OSes and when using non-absolute paths,
    # you should rely on specialized modules, such as "os.path".
    save_dir_path = os.path.abspath(path)
    # Check if the specified path exists.
    if not os.path.exists(save_dir_path):
        # If the path does not exist, then create it.
        try:
            # The "os.makedirs" function for creating a directory with all
            # intermediate directories has an optional argument "mode" - the directory access mode.
            # For example: os.makedirs(save_dir_path, mode = 0o770)
            # A directory will be created along the path "save_dir_path" with permissions: 'rwxrwx---'.
            # The "mode" argument is not applicable for all platforms.
            # When setting permissions for a directory, be careful!
            # For example: os.makedirs(save_dir_path, mode = 0o777).
            # A directory will be created along the path "save_dir_path" with permissions: 'rwxrwxrwx'.
            # Such unrestricted permissions for a directory are a serious threat to the security of your system!
            os.makedirs(save_dir_path)
            print(('\n\t The directory was successfully created in this path:\n\t\t{}'
                  ).format(save_dir_path))
        except Exception:
            # If an error occurred while creating directories,
            # we display detailed information about the exception.
            traceback_print_exc()
            # And we interrupt the further execution of the code.
            cmds.error(('\n\t Failed to create the folder at the specified path:\n\t\t{}'
                       ).format(save_dir_path))
    # Let's create a list with the names of all Maya resource files.
    # Let's use the Maya Python command "cmds.resourceManager()".
    # There are only two flags for this command:
    # nameFilter = string
    # and
    # saveAs = (resource_file_name, save_file_path_with_file_name)
    # !!! If you do not explicitly specify a value for the "nameFilter" flag,
    # then the "nameFilter" flag will still be implicitly initialized with its previous value!
    # For example: cmds.resourceManager(nameFilter = 'p*?tangent*?png')
    # will return a list of four filenames.
    # If after that we run the command without flags:
    # cmds.resourceManager()
    # This will return a list of the same four filenames.
    # To have the default filter display the names of all resource files, use flag nameFilter = '*'
    # In the value string for the "nameFilter" flag, you can use "*" and "?"
    # Character case is ignored.
    # To display the names of all PNG resource files:
    # For example: cmds.resourceManager(nameFilter = '*.png')
    # To display the names of all SVG resource files:
    # For example: cmds.resourceManager(nameFilter = '*.svg')
    # To list the names of all resource files starting with the character "p",
    # containing the character sequence "tangent", and ending with the character sequence "png":
    # For example: cmds.resourceManager(nameFilter = 'p*?tangent*?png')
    all_resourse_list = cmds.resourceManager(nameFilter = name_filter)
    # Let's count the number of filenames in the list of resource files.
    source_count = len(all_resourse_list)
    # We will ask the user for consent to extract the resource files to the specified directory.
    # To do this, we will display a confirmation dialog.
    message_confirm = ('{} Maya resurce files will be extracted to this directory:\n\t{}'
                      ).format(source_count, save_dir_path)
    # Let's get the name of the May window in order to parent the confirmDialog to it.
    maya_window_name = mel.eval('$tmpVar = $gMainWindow;')
    # In our case, confirmDialog can return one of the following values:
    # 'OK' - if the user presses the 'OK' button or the Enter key,
    # "Cancel" - if the user presses the "Cancel" button or the Escape key,
    # ''dismiss' - if the user will close the window in some way.
    # For example, by clicking the 'Close' button in the title bar
    # or by pressing the key combination alt+F4.
    confirm = cmds.confirmDialog(annotation = 'Extract Maya resourse files',
                                      title = 'Extract Maya resourse files',
                                     button = ('OK', 'Cancel'),
                               cancelButton = 'Cancel',
                              defaultButton = 'OK',
                                    message = message_confirm,
                               messageAlign = 'center',
                                     parent = maya_window_name)
    # If the user did not confirm the confirmation dialog,
    # then we display a warning and exit the function, returning a result of 0.
    if confirm != 'OK':
        cmds.warning('\n\t The user changed his mind. Code execution terminated.\n')
        return 0
    start = t_clock()  
    # Let's create a variable to count the number of failed file extractions.
    failed_count = 0
    # For all resource filenames, extract their respective resource files to the "save_dir_path" directory.
    # Let's leave the original names for the extracted resource files.
    for file_name in all_resourse_list:
        try:
            # Let's create a string containing the full path to extract with the file name.
            save_file_path = os.path.join(save_dir_path, file_name)
            # For a specific resource file name (item),
            # extract the corresponding resource file with the original name
            # to the directory "save_dir_path", as "save_file_path".
            cmds.resourceManager(saveAs = (file_name, save_file_path))
        except:
            # In case of unsuccessful extraction of the resource file,
            # we display a warning with the file name:
            cmds.warning('\t Failed to extract file "{}" to specified path!'.format(item))
            # And increase the counter of failed file extractions:
            failed_count += 1
    # We display the results of the function execution.
    # One more confirmation dialog would be redundant. Therefore, we print the message.
    # We display elapsed time in seconds, limiting the value to four decimal places.
    print(('\n\t Complete. Operation time: {:.4f} s.\n\t\t {} out of {} resource files extracted.'
          ).format(t_clock() - start, source_count - failed_count, source_count))
    return 1


# Specify a directory to save the extracted resource files.
path = r'C:\extract_maya_resourse_files'

# Let's execute the function by passing as an argument, only the path for extracting files.
# Since we did not specify an argument for the filter,
# resource files with any names will be extracted to the "path" directory, that is, all files.
extract_maya_resource_files(path)

commands (Python):
resourceManager
confirmDialog

1 Like

Total agree, its look good :star_struck:

#Wrong
importmaya.mel as mel
#Right
import maya.mel as mel

This is Awesome Thnkz a lot!!!

1 Like

Thank you for pointing out this typo!

1 Like