Categories
Tools

Extract Preview Image from SolidWorks document

SolidWorks documents (Parts, Assemblies and Drawings) contain a preview image of their content.

The documents use the Structured Storage mechanism from Microsoft,

http://en.wikipedia.org/wiki/COM_Structured_Storage

and have an element called PreviewPNG which contains the image.

You can use an application such as the Structured Storage Viewer from MiTeC

http://www.mitec.cz/ssv.html

to view the contents of any document based on structured storage.

Alternatively, you may want to access the image directly, and this can be done, for example in Python, as follows.

Here is a code snippet showing how to extract the relevant data.

import glob
import os
import pythoncom
from win32com import storagecon

# =============================================================================
def read_png_from_model( filename ):

    flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE

    try:
        stg = pythoncom.StgOpenStorage( filename, None, flags )

        size = 0
        for e in stg.EnumElements():
            if e[0] == 'PreviewPNG':
                size = e[2]
                break
        else:
            return None

        png = stg.OpenStream( 'PreviewPNG', None, flags ).Read( size )

        del stg

        return png

    except:
        return None

and here is a snippet  showing how to use that code on a directory of SolidWorks documents

if len(sys.argv) < 2:
    print "Specify Directory Path containing SolidWorks Documents."
    sys.exit()
print sys.argv[1]
if os.path.exists(sys.argv[1]) and os.path.isdir(sys.argv[1]):
    os.chdir(sys.argv[1])
    FILE = open(cubewindow,'w')
    FILE.write('var myCubeMenu = new CubeMenu({\n')
    FILE.write('items: [\n')

    for path in glob.glob( '*.sld*'):
        if path[0] == '~':
            print 'Ignoring '+path
            continue
        cubewindow = 'cubeinit.txt'

        name = os.path.splitext( path )[0]
        exten = (os.path.splitext( path )[1]).lower()
        #print 'extension '+exten
        prefix = 'PART_'
        if exten == '.sldasm':
            prefix='ASSM_'
        if exten == '.slddrw':
            prefix='DRAW_'

        filnam=prefix+name+'.png'
        print "filename ",filnam
        bytes = read_png_from_model( path )
        if( bytes ):
            file( filnam, 'wb').write( bytes )
            FILE.write("['"+name+"', 'data/"+filnam+"', function(){Message.show('Open "+name+"'); }],\n")
    FILE.write("]\n")
    FILE.write("});\n")
    FILE.close()
else:
    print "Cannot attach to directory ", sys.argv[1]