#include once "window9.bi"

Using GDIPLUS

Dim shared ULONG_PTR_01 AS ULONG_PTR
DIM GDIPLUSSTARTUPINPUT_01 AS GDIPLUSSTARTUPINPUT
GDIPLUSSTARTUPINPUT_01.GdiplusVersion = 1
IF (GDIPLUSSTARTUP(@ULONG_PTR_01, @GDIPLUSSTARTUPINPUT_01, NULL) <> 0) THEN
	PRINT "FAIL"
End If

Sub Save_Image(ByVal hBitmap As HBITMAP, ByRef sFileName As USTRING) Export
	Dim As String sClssid
	Dim As WString Ptr wbuf
	dim as integer nChars,result
	Dim As GpBitmap Ptr GPIMAGE_01
	DIM AS CLSID CLSID_01
	
	If LCase(Right(sFileName,4))=".bmp" Then
		sClssid="{557CF400-1A04-11D3-9A73-0000F81EF32E}"
	ElseIf LCase(Right(sFileName,5))=".jpeg" Or LCase(Right(sFileName,4))=".jpg" Then
		sClssid="{557CF401-1A04-11D3-9A73-0000F81EF32E}"
	ElseIf LCase(Right(sFileName,4))=".gif" Then
		sClssid="{557CF402-1A04-11D3-9A73-0000F81EF32E}"
	ElseIf LCase(Right(sFileName,5))=".tiff" Then
		sClssid="{557CF405-1A04-11D3-9A73-0000F81EF32E}"
	ElseIf LCase(Right(sFileName,4))=".png" Then
		sClssid="{557CF406-1A04-11D3-9A73-0000F81EF32E}"
	End If
	if len(sClssid)=0 then Exit sub
	
	GdipCreateBitmapFromHBITMAP(hBitmap, NULL, @GPIMAGE_01)
	CLSIDFROMSTRING WSTR(sClssid), @CLSID_01
	#ifdef UNICODE
		result=GDIPSaveImageToFile(Cast(GpImage Ptr,GPIMAGE_01), *sFileName, @CLSID_01 , 0)		
	#else	
		nChars = (Len(sFileName)*2)+2
		wbuf  = callocate( nChars)
		if wbuf then
			MultiByteToWideChar(CP_ACP, 0, StrPtr(sFileName), -1, wbuf, nChars)
			result=GDIPSaveImageToFile(Cast(GpImage Ptr,GPIMAGE_01), *wbuf, @CLSID_01 , 0)
			deallocate wbuf
		endif
	#EndIf
	GDIPDisposeImage(Cast(GpImage Ptr,GPIMAGE_01))
End Sub
