19 out of 52 rated this helpful - Rate this topic

LoadImage function

Applies to: desktop apps only

Loads an icon, cursor, animated cursor, or bitmap.

Syntax

HANDLE WINAPI LoadImage(
  __in_opt  HINSTANCE hinst,
  __in      LPCTSTR lpszName,
  __in      UINT uType,
  __in      int cxDesired,
  __in      int cyDesired,
  __in      UINT fuLoad
);

Parameters

hinst [in, optional]

Type: HINSTANCE

A handle to the module of either a DLL or executable (.exe) that contains the image to be loaded. For more information, see GetModuleHandle. Note that as of 32-bit Windows, an instance handle (HINSTANCE), such as the application instance handle exposed by system function call of WinMain, and a module handle (HMODULE) are the same thing.

To load an OEM image, set this parameter to NULL.

To load a stand-alone resource (icon, cursor, or bitmap file)—for example, c:\myimage.bmp—set this parameter to NULL.

lpszName [in]

Type: LPCTSTR

The image to be loaded. If the hinst parameter is non-NULL and the fuLoad parameter omits LR_LOADFROMFILE, lpszName specifies the image resource in the hinst module. If the image resource is to be loaded by name from the module, the lpszName parameter is a pointer to a null-terminated string that contains the name of the image resource. If the image resource is to be loaded by ordinal from the module, use the MAKEINTRESOURCE macro to convert the image ordinal into a form that can be passed to the LoadImage function. For more information, see the Remarks section below.

If the hinst parameter is NULL and the fuLoad parameter omits the LR_LOADFROMFILE value, the lpszName specifies the OEM image to load. The OEM image identifiers are defined in Winuser.h and have the following prefixes.

PrefixMeaning
OBM_OEM bitmaps
OIC_OEM icons
OCR_OEM cursors

 

To pass these constants to the LoadImage function, use the MAKEINTRESOURCE macro. For example, to load the OCR_NORMAL cursor, pass MAKEINTRESOURCE(OCR_NORMAL) as the lpszName parameter, NULL as the hinst parameter, and LR_SHARED as one of the flags to the fuLoad parameter.

If the fuLoad parameter includes the LR_LOADFROMFILE value, lpszName is the name of the file that contains the stand-alone resource (icon, cursor, or bitmap file). Therefore, set hinst to NULL.

uType [in]

Type: UINT

The type of image to be loaded. This parameter can be one of the following values.

ValueMeaning
IMAGE_BITMAP
0

Loads a bitmap.

IMAGE_CURSOR
2

Loads a cursor.

IMAGE_ICON
1

Loads an icon.

 

cxDesired [in]

Type: int

The width, in pixels, of the icon or cursor. If this parameter is zero and the fuLoad parameter is LR_DEFAULTSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width. If this parameter is zero and LR_DEFAULTSIZE is not used, the function uses the actual resource width.

cyDesired [in]

Type: int

The height, in pixels, of the icon or cursor. If this parameter is zero and the fuLoad parameter is LR_DEFAULTSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the height. If this parameter is zero and LR_DEFAULTSIZE is not used, the function uses the actual resource height.

fuLoad [in]

Type: UINT

This parameter can be one or more of the following values.

ValueMeaning
LR_CREATEDIBSECTION
0x00002000

When the uType parameter specifies IMAGE_BITMAP, causes the function to return a DIB section bitmap rather than a compatible bitmap. This flag is useful for loading a bitmap without mapping it to the colors of the display device.

LR_DEFAULTCOLOR
0x00000000

The default flag; it does nothing. All it means is "not LR_MONOCHROME".

LR_DEFAULTSIZE
0x00000040

Uses the width or height specified by the system metric values for cursors or icons, if the cxDesired or cyDesired values are set to zero. If this flag is not specified and cxDesired and cyDesired are set to zero, the function uses the actual resource size. If the resource contains multiple images, the function uses the size of the first image.

LR_LOADFROMFILE
0x00000010

Loads the stand-alone image from the file specified by lpszName (icon, cursor, or bitmap file).

LR_LOADMAP3DCOLORS
0x00001000

Searches the color table for the image and replaces the following shades of gray with the corresponding 3-D color.

  • Dk Gray, RGB(128,128,128) with COLOR_3DSHADOW
  • Gray, RGB(192,192,192) with COLOR_3DFACE
  • Lt Gray, RGB(223,223,223) with COLOR_3DLIGHT

Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.

LR_LOADTRANSPARENT
0x00000020

Retrieves the color value of the first pixel in the image and replaces the corresponding entry in the color table with the default window color (COLOR_WINDOW). All pixels in the image that use that entry become the default window color. This value applies only to images that have corresponding color tables.

Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.

If fuLoad includes both the LR_LOADTRANSPARENT and LR_LOADMAP3DCOLORS values, LR_LOADTRANSPARENT takes precedence. However, the color table entry is replaced with COLOR_3DFACE rather than COLOR_WINDOW.

LR_MONOCHROME
0x00000001

Loads the image in black and white.

LR_SHARED
0x00008000

Shares the image handle if the image is loaded multiple times. If LR_SHARED is not set, a second call to LoadImage for the same resource will load the image again and return a different handle.

When you use this flag, the system will destroy the resource when it is no longer needed.

Do not use LR_SHARED for images that have non-standard sizes, that may change after loading, or that are loaded from a file.

When loading a system icon or cursor, you must use LR_SHARED or the function will fail to load the resource.

This function finds the first image in the cache with the requested resource name, regardless of the size requested.

LR_VGACOLOR
0x00000080

Uses true VGA colors.

 

Return value

Type: HANDLE

If the function succeeds, the return value is the handle of the newly loaded image.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If IS_INTRESOURCE(lpszName) is TRUE, then lpszName specifies the integer identifier of the given resource. Otherwise, it is a pointer to a null- terminated string. If the first character of the string is a pound sign (#), then the remaining characters represent a decimal number that specifies the integer identifier of the resource. For example, the string "#258" represents the identifier 258.

When you are finished using a bitmap, cursor, or icon you loaded without specifying the LR_SHARED flag, you can release its associated memory by calling one of the functions in the following table.

ResourceRelease function
Bitmap DeleteObject
Cursor DestroyCursor
Icon DestroyIcon

 

The system automatically deletes these resources when the process that created them terminates; however, calling the appropriate function saves memory and decreases the size of the process's working set.

Examples

For an example, see Using Window Classes.

Requirements

Minimum supported client

Windows 2000 Professional

Minimum supported server

Windows 2000 Server

Header

Winuser.h (include Windows.h)

Library

User32.lib

DLL

User32.dll

Unicode and ANSI names

LoadImageW (Unicode) and LoadImageA (ANSI)

See also

Reference
CopyImage
LoadCursor
LoadIcon
Conceptual
Resources
Other Resources
GetSystemMetrics
LoadBitmap

 

 

Send comments about this topic to Microsoft

Build date: 2/3/2012

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Using the recommended LoadImage over using the legacy LoadCursor: C example
/D) ;
Using the recommended LoadImage over using the legacy LoadCursor: C example

You need to also define OEMRESOURCE in your resource header file: resource.h
 
"// resource.h" #define OEMRESOURCE
 // MyApp.c
// Initializing the Window Class in WinMain
 
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
        WNDCLASS wc ;         
        wc.hCursor = LoadImage((HINSTANCE)NULL, MAKEINTRESOURCE(OCR_NORMAL),  IMAGE_CURSOR, 0, 0, LR_SHARED) ;

Using the recommended LoadImage over using the legacy LoadCursor: C example
aa
RE: LoadImage Error

Not all WinAPI functions set last-error (the value further returned by GetLastError) to zero in case of success.
One mistake often made by programmers is to call GetLastError without previously checking if the given function has failed or not.
That leads in false assumptions like "LoadImage with LR_CREATEDIBSECTION flag set, alwais fails under Windows XP".

The correct usage of GetLastError is:  

   HBITMAP hBitmap = (HBITMAP)::LoadImage(NULL, pszFileName,
      IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION);
   // if LoadImage fails, it returns a NULL handle
   if(NULL == hBitmap)
   {
      // LoadImage faled so get extended error information.
      DWORD dwError = ::GetLastError();


   }






I posted more details in these FAQs:
http://www.codeguru.com/forum/showthread.php?t=515569
http://www.codexpert.ro/forum/viewtopic.php?f=31&t=1841  (RO)

LoadImage Error
hBmp = (HBITMAP)LoadImage(NULL,"background.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION); $0$0 $0 $0"background.bmp" is a 24 bit bmp, generated with Paint.$0 $0I get always de error code 8 (ERROR_NOT_ENOUGH_MEMORY) with GetLastError() on win xp. On win7 it works ok.$0 $0$0 $0 $0Any idea?$0 $0$0 $0 $0Thanks.$0
Works lol
HBITMAP b = LoadImage(NULL, "c:\\background.bmp", IMAGE_BITMAP, 0, 0, 0x00000010); //returns a valid HBITMAP. AND IT WORKS xD im new to c++ ^^ only started a day ago lol $0$0 $0 $0however yeah that got it to work but now get a $0 $0$0 $0 $0"error C2664: 'LoadImageW' : cannot convert parameter 2 from 'const char [18]' to 'LPCWSTR' $01>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast"    $0 $0$0 $0 $0I would say that is because of the code written there but it sounds like something else to me any ideas 0o$0 $0 $0 $0
LoadImage Error
HBITMAP b = LoadImage(NULL, _T("c:\test.bmp"), IMAGE_BITMAP, 0, 0, IR_LOADFROMFILE); //returns a valid HBITMAP.

CString c = _T("c:\test.bmp");
HBITMAP b = LoadImage(NULL, c, IMAGE_BITMAP, 0, 0, IR_LOADFROMFILE); //returns NULL with GetLastError of ERROR_FILE_NOT_FOUND

I don't understand why.

First of all, _T("c:\test.bmp") is not a valid filename. It contains an embedded horizontal tab. Maybe you want _T("c:\\test.bmp").
override LoadImage
...
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);
...
Image LoadImage(string filename)
{
    byte[] bytes = File.ReadAllBytes(filename);
    Size size = new Size();

    using (MemoryStream stream = new MemoryStream(bytes))
    {
        try
        {
            Image image = Image.FromStream(stream, false, true);
            return image;
        }
        catch
        {
            Image image = Image.FromStream(stream, false, false);
            size = new Size(img.Width, img.Height);
        }
    }

    IntPtr ipImage = LoadImage(IntPtr.Zero, filename, 0, size.Width, size.Height, 0x00000010);
    return Image.FromHbitmap(ipImage);
}
...
list with OEM constants
below is a list of the system defined bitmaps/icons/cursors

note 1: for instance the LoadIcon constants IDI_xxx are equal to the LoadImage counterparts.

note 2: LoadImage fails to load system defined icons if LR_SHARED is not specified.



#define OBM_BTNCORNERS 32758
#define OBM_BTSIZE 32761
#define OBM_CHECK 32760
#define OBM_CHECKBOXES 32759
#define OBM_CLOSE 32754
#define OBM_COMBO 32738
#define OBM_DNARROW 32752
#define OBM_DNARROWD 32742
#define OBM_DNARROWI 32736
#define OBM_LFARROW 32750
#define OBM_LFARROWI 32734
#define OBM_LFARROWD 32740
#define OBM_MNARROW 32739
#define OBM_OLD_CLOSE 32767
#define OBM_OLD_DNARROW 32764
#define OBM_OLD_LFARROW 32762
#define OBM_OLD_REDUCE 32757
#define OBM_OLD_RESTORE 32755
#define OBM_OLD_RGARROW 32763
#define OBM_OLD_UPARROW 32765
#define OBM_OLD_ZOOM 32756
#define OBM_REDUCE 32749
#define OBM_REDUCED 32746
#define OBM_RESTORE 32747
#define OBM_RESTORED 32744
#define OBM_RGARROW 32751
#define OBM_RGARROWD 32741
#define OBM_RGARROWI 32735
#define OBM_SIZE 32766
#define OBM_UPARROW 32753
#define OBM_UPARROWD 32743
#define OBM_UPARROWI 32737
#define OBM_ZOOM 32748
#define OBM_ZOOMD 32745

#define OCR_NORMAL 32512
#define OCR_IBEAM 32513
#define OCR_WAIT 32514
#define OCR_CROSS 32515
#define OCR_UP 32516
#define OCR_SIZE 32640
#define OCR_ICON 32641
#define OCR_SIZENWSE 32642
#define OCR_SIZENESW 32643
#define OCR_SIZEWE 32644
#define OCR_SIZENS 32645
#define OCR_SIZEALL 32646
#define OCR_NO 32648
#define OCR_APPSTARTING 32650

#define OIC_SAMPLE 32512
#define OIC_HAND 32513
#define OIC_QUES 32514
#define OIC_BANG 32515
#define OIC_NOTE 32516
#define OIC_WINLOGO 32517
#define OIC_WARNING OIC_BANG
#define OIC_ERROR OIC_HAND
#define OIC_INFORMATION OIC_NOTE
LoadImage() behavior on Vista for loading Jpg images
I found that I can't load jpg image using this API on Vista. I can load bmp files properly.
Is anything changed for Vista?

[tfl - 02 08 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
Re: LoadImage Error
Try CString c = _T("c:\\test.bmp");
C# Interop Definition
[Serializable]
internal enum ImageType
{
Bitmap = 0,
Icon = 1,
Cursor = 2,
EnhMetafile = 3,
}

[Serializable, Flags]
internal enum LoadImageFlags
{
DefaultColor = 0x0,
Monochrome = 0x1,
Color = 0x2,
CopyReturnOriginal = 0x4,
CopyDeleteOriginal = 0x8,
LoadFromFile = 0x10,
LoadTransparent = 0x20,
DefaultSize = 0x40,
VgaColor = 0x80,
LoadMap3DColors = 0x1000,
CreateDibSection = 0x2000,
CopyFromResource = 0x4000,
Shared = 0x8000,
}

#region user32!LoadImage

[DllImport(Dll.User32, CharSet = CharSet.Auto, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static extern IntPtr LoadImage(
[In] IntPtr hinst,
[In] String lpszName,
[In] ImageType uType,
[In] Int32 cxDesired,
[In] Int32 cyDesired,
[In] LoadImageFlags fuLoad
);

#endregion
Return type
Note that although the return type is HANDLE, the function does not return a Kernel object handle. It returns:
  • For IMAGE_ICON: a USER object handle.
  • For IMAGE_CURSOR: a USER object handle.
  • For IMAGE_BITMAP: a GDI object handle.
There is no generic typedef for USER handles. Generic GDI handles use the typedef HGDIOBJ, which is the parameter type accepted by DeleteObject().