#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GDIPlus.au3>

Global $hGui, $btnOpen, $iPic, $hBMP, $OpenFile

$hGui = GUICreate("Просмотрщик рисунков", 360, 400)
GUICtrlCreateGroup("Предпросмотр", 10, 5, 342, 351)
$iPic = GUICtrlCreatePic("", 16, 20, 330, 330)
$btnOpen = GUICtrlCreateButton("Открыть", 270, 363, 80, 30)
GUISetState()

While 1
	Switch GUIGetMsg()
		Case $btnOpen
			$OpenFile = FileOpenDialog('Открыть', @WorkingDir, 'Рисунок (*.bmp;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff)', '', '', $hGui)
			If @error Then ContinueLoop
			$hBMP = _GetImage($OpenFile, 330, BitOR(0xFF000000, _GetGuiBkColor(_WinAPI_GetForegroundWindow())))
			_hBmpToPicControl($iPic, $hBMP, 1)
		Case $GUI_EVENT_CLOSE
			Exit
	EndSwitch
WEnd

Func _GetImage($sFile, $iWH, $iBkClr = 0xFFFFFF)
	Local $hBmp1, $hBitmap, $hGraphic, $hImage, $iW, $iH, $aGS, $hBmp2
	_GDIPlus_Startup()
	$hBmp1 = _WinAPI_CreateBitmap($iWH, $iWH, 1, 32)
	$hBitmap = _GDIPlus_BitmapCreateFromHBITMAP($hBmp1)
	$hGraphic = _GDIPlus_ImageGetGraphicsContext($hBitmap)
	_WinAPI_DeleteObject($hBmp1)
	_GDIPlus_GraphicsClear($hGraphic, BitOR(0xFF000000, $iBkClr))
	$hImage = _GDIPlus_ImageLoadFromFile($sFile)
	$iW = _GDIPlus_ImageGetWidth($hImage)
	$iH = _GDIPlus_ImageGetHeight($hImage)
	$aGS = _GetScale($iW, $iH, $iWH)
	_GDIPlus_GraphicsDrawImageRect($hGraphic, $hImage, $aGS[0], $aGS[1], $aGS[2], $aGS[3])
	_GDIPlus_ImageDispose($hImage)
	_GDIPlus_GraphicsDispose($hGraphic)
	$hBmp2 = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap)
	_GDIPlus_BitmapDispose($hBitmap)
	_GDIPlus_Shutdown()
	Return $hBmp2
EndFunc   ;==>_GetImage

; Подстраивает размеры для вмещения в Pic
Func _GetScale($iW, $iH, $iWH)
	Local $aRet[4]
	If $iW <= $iWH And $iH <= $iWH Then
		$aRet[2] = $iW
		$aRet[3] = $iH
		$aRet[0] = ($iWH - $aRet[2]) / 2
		$aRet[1] = ($iWH - $aRet[3]) / 2
	ElseIf $iW > $iH Then
		$aRet[2] = $iWH
		$aRet[3] = $iH / ($iW / $iWH)
		$aRet[0] = 0
		$aRet[1] = ($iWH - $aRet[3]) / 2
	ElseIf $iW < $iH Then
		$aRet[2] = $iW / ($iH / $iWH)
		$aRet[3] = $iWH
		$aRet[0] = ($iWH - $aRet[2]) / 2
		$aRet[1] = 0
	ElseIf $iW = $iH Then
		$aRet[2] = $iWH
		$aRet[3] = $iWH
		$aRet[0] = 0
		$aRet[1] = 0
	EndIf
	Return $aRet
EndFunc   ;==>_GetScale

; Устанавливает рисунок в элемент Pic
Func _hBmpToPicControl($iCtrlID, ByRef $hBMP, $iFlag = 0)
	Local Const $STM_SETIMAGE = 0x0172
	Local Const $IMAGE_BITMAP = 0
	Local $hOldBmp = GUICtrlSendMsg($iCtrlID, $STM_SETIMAGE, $IMAGE_BITMAP, $hBMP)
	If $hOldBmp Then _WinAPI_DeleteObject($hOldBmp)
	If $iFlag Then _WinAPI_DeleteObject($hBMP)
EndFunc   ;==>_hBmpToPicControl

Func _GetGuiBkColor($hWnd)
	Local $hDC, $aBGR
	$hDC = _WinAPI_GetDC($hWnd)
	$aBGR = DllCall('gdi32.dll', 'int', 'GetBkColor', 'hwnd', $hDC)
	_WinAPI_ReleaseDC($hWnd, $hDC)
	Return BitOR(BitAND($aBGR[0], 0x00FF00), BitShift(BitAND($aBGR[0], 0x0000FF), -16), BitShift(BitAND($aBGR[0], 0xFF0000), 16))
EndFunc   ;==>_GetGuiBkColor