#coding: gbk

from ctypes import *
from ctypes.wintypes import *
from comtypes import GUID

oleaut32 = windll.oleaut32
gdiplus = windll.gdiplus


class GdiplusStartupInput(Structure):
    _fields_ = [
        ('GdiplusVersion', c_uint32),
        ('DebugEventCallback', c_void_p),
        ('SuppressBackgroundThread', BOOL),
        ('SuppressExternalCodecs', BOOL)
    ]

class GdiplusStartupOutput(Structure):
    _fields = [
        ('NotificationHookProc', c_void_p),
        ('NotificationUnhookProc', c_void_p)
    ]


class PicDesc(Structure):
    _fields_ = [
        ('Size', UINT),
        ('Type', UINT),
        ('hPic', HBITMAP),
        ('hPal', HPALETTE)
    ]

PICTYPE_BITMAP = 1

def LoadImage(filename):
    '''Load an image from a file.
    '''

    #Initaialize GDI+
    token = c_ulong()
    startup_in = GdiplusStartupInput()
    startup_in.GdiplusVersion = 1
    startup_out = GdiplusStartupOutput()
    u = gdiplus.GdiplusStartup( byref(token), byref(startup_in), byref(startup_out))

    fname = LPOLESTR( filename )
    bitmap = c_void_p()
    gdiImage = c_void_p()
    x = LPVOID()
        
    if u == 0:
        print u
        #Load the image
        v = gdiplus.GdipCreateBitmapFromFile( fname, byref(gdiImage) )
        if v == 0:
            print v

            #Create a bitmap handle from the GDI image
            gdiplus.GdipCreateHBITMAPFromBitmap( gdiImage, byref(bitmap), 0 )

            #Create the IPicture object from the bitmap handle
            IID_IPicture = GUID('{7BF80980-BF32-101A-8BBB-00AA00300CAB}' )
            picinfo = PicDesc( Type=PICTYPE_BITMAP, hPic=bitmap, hPal=0  )
            picinfo.Size = picinfo.__sizeof__()
            
            print oleaut32.OleCreatePictureIndirect( byref(picinfo), byref(IID_IPicture), True, byref(x) )
            
            gdiplus.GdipDisposeImage( gdiImage)

        gdiplus.GdiplusShutdown( token )
        
    #from comtypes.automation import VARIANT, IUnknown    
    return x # cast(x,POINTER(IUnknown))
    
    
if __name__ == '__main__':

    fname = 'c:/edit.png' 
    x = LoadImage(fname)
    
    
    
