Click here to Skip to main content
6,595,444 members and growing! (16,514 online)
Email Password   helpLost your password?
Multimedia » General Graphics » General     Intermediate

Rendering GIF, JPEG, Icon, or Bitmap Files with OleLoadPicture

By Wes Rogers

Easy way to do basic rendering of image files into a view window
VC6, Windows, Visual Studio, MFC, Dev
Posted:26 Sep 2000
Views:245,787
Bookmarked:72 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
41 votes for this article.
Popularity: 6.72 Rating: 4.17 out of 5
1 vote, 6.3%
1
2 votes, 12.5%
2
1 vote, 6.3%
3
3 votes, 18.8%
4
9 votes, 56.3%
5

Sample Image - render.gif

Introduction

This article describes a simple way to do basic rendering of various types of image files into a view window.

It uses a rendering method described in the MSDN article Q218972, LOADPIC.EXE.

I ran across this sample application purely by accident. After reviewing it, I re-wrote the guts of the functionality for use in an MFC document-view environment.

The re-write consists of three functions:

  • DrawImage(), which draws the image contained in an image file.
  • GetImageSize(), which returns the height and width of the image in the image file.
  • LoadPictureFile(), which loads the image from disk and readies it for display via OleLoadPicture().

Header Definitions:

BOOL DrawImage(CDC*    pDC,         //Device context

               CString csFile,      //Pathname to image file

               CPoint  ptCenter,    //Center point for image

               HWND    hWnd,        //Handle to view window

               CRect   rectImage);  //Display area rectangle

DrawImage() will render the image whose pathname is passed in in csFile into the area of the rectangle in rectImage.

rectImage must be in device units.

Important: These functions assume a DC mapping mode other than MM_TEXT. That is, negative Y is downward.

If you are going to use MM_TEXT, you will need to change the signs of the height variables in the Render() function call.

BOOL GetImageSize(CDC*    pDC,       //Device context

                  LPCTSTR szFile,    //Pathname to image file

                  int*    pnHeight,  //Height to return

                  int*    pnWidth);  //Width to return

GetImageSize() returns the height and width of the image in szFile. These values are in device units for the DC passed in to the function.

It is good to use this function to fetch the true size of the image, in case you want to let the user reset the image display.

BOOL LoadPictureFile(LPCTSTR    szFile,      //Image file pathname

                     LPPICTURE* pgpPicture); //Ptr to PICTURE for image

LoadPictureFile() loads the image bytes in szFile into pgpPicture.

Includes:

The LOADPIC project has a reference to olectl.h in its stdafx.h file.

However, I am using these functions in an MFC application with no special includes.

MSDN does not mention any need for OleLoadPicture.

Source:

BOOL DrawImage(CDC*    pDC,
               CString csFile,
               CPoint  ptCenter,
               HWND    hWnd,
               CRect   rectImage)
{
    if (pDC == NULL || csFile.IsEmpty() || hWnd == NULL)
        return FALSE;
    
    LPPICTURE gpPicture = NULL;
        
    if (LoadPictureFile((LPCTSTR)csFile,&gpPicture))
    {
        //Get width and height of picture

        long hmWidth  = 0;
        long hmHeight = 0;

        gpPicture->get_Width (&hmWidth);
        gpPicture->get_Height(&hmHeight);

        //Use to get height and width for display

        CRect rectI = rectImage;
        rectI.NormalizeRect();

        int nWidth = rectI.Width();
        int nHeight= rectI.Height();

        CPoint ptUL(ptCenter.x-(nWidth /2),
                    ptCenter.y+(nHeight/2));

		RECT rc;
		GetClientRect(hWnd, &rc);

        HRESULT hrP = NULL;
        
        hrP =
        gpPicture->Render(pDC->m_hDC,
                          ptUL.x,
                          ptUL.y,
                          nWidth,
                          -nHeight,
                          0,
                          hmHeight,
                          hmWidth,
                          -hmHeight,
                          &rc);

        gpPicture->Release();

        if (SUCCEEDED(hrP))
            return TRUE;
    }

    return FALSE;
}

BOOL GetImageSize(CDC*       pDC,
                  LPCTSTR    szFile,
                  int*       pnHeight,
                  int*       pnWidth)
{
    LPPICTURE gpPicture = NULL;

    if (!LoadPictureFile(szFile,&gpPicture))
        return FALSE;

    //Get width and height of picture

    long hmWidth  = 0;
    long hmHeight = 0;

    gpPicture->get_Width (&hmWidth);
    gpPicture->get_Height(&hmHeight);

    int nPixX = pDC->GetDeviceCaps(LOGPIXELSX);
    int nPixY = pDC->GetDeviceCaps(LOGPIXELSY);

    //For printers, pixels per inch is really DPI, so be careful!

    if (pDC->IsPrinting())
    {
		nPixX = 96;
        nPixY = 96;
    }

    //Convert to device units

    *pnWidth  = MulDiv(hmWidth,  nPixX, HIMETRIC_INCH);
    *pnHeight = MulDiv(hmHeight, nPixY, HIMETRIC_INCH);

    return TRUE;
}

BOOL LoadPictureFile(LPCTSTR    szFile,
                     LPPICTURE* pgpPicture)
{
    // open file

    HANDLE hFile = CreateFile(szFile,
                              GENERIC_READ,
                              0,
                              NULL,
                              OPEN_EXISTING,
                              0,
                              NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        AfxMessageBox ("Could not read file");
        return FALSE;
    }

    // get file size

    DWORD dwFileSize = GetFileSize(hFile, NULL);

    if (dwFileSize == (DWORD)-1)
    {
        CloseHandle(hFile);
        AfxMessageBox ("File seems to be empty");
        return FALSE;
    }

    LPVOID pvData = NULL;

    // alloc memory based on file size

    HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);

    if (hGlobal == NULL)
    {
        CloseHandle(hFile);
        AfxMessageBox ("Could not allocate memory for image");
        return FALSE;
    }

    pvData = GlobalLock(hGlobal);

    if (pvData == NULL)
    {
        GlobalUnlock(hGlobal);
        CloseHandle(hFile);
        AfxMessageBox ("Could not lock memory for image");
        return FALSE;
    }

    DWORD dwBytesRead = 0;

    // read file and store in global memory

    BOOL bRead = ReadFile(hFile,
                          pvData,
                          dwFileSize,
                          &dwBytesRead,
                          NULL);

    GlobalUnlock(hGlobal);
    CloseHandle(hFile);

    if (!bRead)
    {
        AfxMessageBox ("Could not read file");
        return FALSE;
    }

    LPSTREAM pstm = NULL;

    // create IStream* from global memory

    HRESULT hr = CreateStreamOnHGlobal(hGlobal,
                                       TRUE,
                                       &pstm);

    if (!(SUCCEEDED(hr)))
    {
        AfxMessageBox ("CreateStreamOnHGlobal() failed");

        if (pstm != NULL)
            pstm->Release();
            
        return FALSE;
    }

    else if (pstm == NULL)
    {
        AfxMessageBox ("CreateStreamOnHGlobal() failed");
        return FALSE;
    }

	// Create IPicture from image file

	if (*pgpPicture)
		(*pgpPicture)->Release();

    hr = ::OleLoadPicture(pstm,
                          dwFileSize,
                          FALSE,
                          IID_IPicture,
                          (LPVOID *)&(*pgpPicture));

    if (!(SUCCEEDED(hr)))
    {
    	pstm->Release();
        AfxMessageBox("Could not load image (hr failure)");
        return FALSE;
    }

    else if (*pgpPicture == NULL)
    {
    	pstm->Release();
        AfxMessageBox("Could not load image (pgpPicture failure)");
        return FALSE;
    }

    pstm->Release();

    return TRUE;  //Made it ...!

}

Example of Use:

The picture above shows use of these functions in a map-making program I have been working on.

Here is how the program uses them:

Document Class:

First a handler for the "Map" menu allows a user to navigate to the desired image file and open it. This simply saves off the file path for use later, and sets the program into "rendering images" mode: Wherever the user clicks, a stroke "image" object will be created to display the image.

The CStroke class handles this (remember Scribble?).

View Class:

Once the program is in "rendering images" mode, the view class handles the left mouse button click. Here is the code block from OnLButtonDown():

void CGameMaprView::OnLButtonDown(UINT nFlags, CPoint point) 
{
    CGameMaprDoc* pDoc = GetDocument();
    CRect rectTemp;

    CClientDC dc(this);
    OnPrepareDC(&dc);
    dc.DPtoLP(&point);

    ...


    //---------------------------------------

    else if (pDoc->DrawType() == DRAW_IMAGE_FILE)
    {
        m_pStrokeCur = pDoc->NewStroke(FALSE,
                                       &dc,
                                       point.x,
                                       point.y,
                                       pDoc->BitmapResourceName()); //Pathname to image file


        if (m_pStrokeCur != NULL)
        {
            m_pStrokeCur->DrawStroke(&dc,FALSE,this);

            //Invalidate for re-display

            pDoc->RedrawArea(m_pStrokeCur->m_rectBounding);
        }
    }

    ...

    return;
}

Document Class (again):

Back in the document class, NewStroke() creates a new stroke, and gets the original image size for the initial bounding box:

CStroke* CGameMaprDoc::NewStroke(BOOL bPasting,
                                 CDC  *pDC,
                                 int  nX,
                                 int  nY,
                                 CString csBmp) //Image file in this case...

{

    ...


    else if (m_eDrawType == DRAW_IMAGE_FILE)
    {
        eType = S_TYPE_IMAGE_FILE;
    }

    pStrokeItem = new CStroke( ... );

	...

    //Do bitmap-related processing

    else if (m_eDrawType == DRAW_IMAGE_FILE &&
             !csBmp.IsEmpty())
    {
        int nH = 0;
        int nW = 0;

        //Set the original size of the image

        if (GetImageSize(pDC,(LPCTSTR)csBmp,&nH,&nW))
        {            
            pStrokeItem->m_csBitmapResource = csBmp;
            pStrokeItem->m_rectBounding.SetRect(nX-(nW/2),
                                                nY+(nH/2),
                                                nX+(nW/2),
                                                nY-(nH/2));
        }

        else
        {
            AfxMessageBox("Could not create image object");
            delete pStrokeItem;
            return NULL;
        }
    }

    ...
}

Stroke Class:

In the CStroke class, the DrawStroke() function handles drawing of the image:
BOOL CStroke::DrawStroke(CDC*           pDC,
                         BOOL           bDirectDisplay,
                         CGameMaprView* pView)
{

    ...


    //Render an image file-----------------------

    else if (StrokeType() == S_TYPE_IMAGE_FILE)
    {
        DrawImage(pDC,
                  m_csBitmapResource,
                  m_rectBounding.CenterPoint(),
                  pView->m_hWnd,
                  m_rectBounding);
    }

    ...

}

The stroke class also has an "update properties" method that allows a user to specify a different height and width for the image.

Printing Issues:

For some reason, articles dealing with images (especially bitmaps) never talk about printing issues to consider.

The biggest one is the aspect ratio:

LOGPIXELSX and LOGPIXELSY, to a printer's Device Context (DC) mean the number of Dots Per Inch (DPI). On a 600 DPI printer, these values will be returned as 600.

If you are not careful, this will have "interesting" results when you print!

The second issue is transparency. Hewlett-Packard printers, for example, do not seem to recognize the BitBlt ROP codes properly, making it impossible to render an image transparently by the normally-shown methods.

(This may have been fixed on later models - HP never responded when I tried to contact them about it.)

This limitation also exists in the above functions: You will not be able to print a transparent image (such as the knight in the image sample above) using OleLoadImage(). Non-transparent printing seems to work fine.

To do transparent printing, you would need to turn the image into a bitmap, and then print it using regions of color rather than bit-blitting with the "true mask" method.

Failures to Load:

LOADPIC states that it will open Enhanced metafiles and Windows metafiles (EMF and WMF formats).

I successfully loaded two EMF's; however, when I tried to load c:\windows\system\spbanner.wmf, I got:

"Could not load image (hr failure)". Word 97 would not load this file properly either.

If desired, a reader could add further analysis code to list the detailed cause of such failures.

Conclusion:

I have found these functions very useful; it is my hope that other readers will also find them useful for rendering various types of images.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Wes Rogers


Member

Location: United States United States

Other popular General Graphics articles:

  • A flexible charting library for .NET
    Looking for a way to draw 2D line graphs with C#? Here's yet another charting class library with a high degree of configurability, that is also easy to use.
  • CxImage
    CxImage is a C++ class to load, save, display, transform BMP, JPEG, GIF, PNG, TIFF, MNG, ICO, PCX, TGA, WMF, WBMP, JBG, J2K images.
  • 3D Pie Chart
    A class library for drawing 3D pie charts.
  • Barcode Image Generation Library
    This library was designed to give an easy class for developers to use when they need to generate barcode images from a string of data.
  • ImageStone
    An article on a library for image manipulation.
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 69 (Total in Forum: 69) (Refresh)FirstPrevNext
GeneralDisplaying animated GIF's PinmemberTushar Jadhav22:45 23 May '08  
GeneralRotating an Image PinmemberAlex Evans10:30 4 Jan '05  
GeneralError C2065 PinmemberMEDJAI3:20 12 Nov '04  
GeneralRe: Error C2065 PinsussAnonymous13:43 5 May '05  
GeneralTo Load Tif PinmemberSagarika22:45 16 Feb '04  
Generalhow can i render a picture and make the picture gray? PinsussAnonymous22:44 6 Dec '03  
GeneralPortable Network Graphics PinmemberDhirendra20:03 20 Feb '03  
GeneralConverting Jpeg's to numbers in C or C++ PinsussAtomRiot11:20 24 Oct '02  
GeneralRe: Converting Jpeg's to numbers in C or C++ PinmemberChristian Graus11:33 24 Oct '02  
GeneralRe: Converting Jpeg's to numbers in C or C++ Pinsussboggs15:49 17 Feb '05  
GeneralUpside down picture PinsussAnonymous16:48 27 Sep '02  
GeneralRe: Upside down picture PinsussAnonymous17:01 27 Sep '02  
GeneralRe: Upside down picture PinsussFrancis Stafki12:10 20 Nov '02  
Generalhow to change .bmp files to .jpg files PinsussLong zhiyi20:34 23 Sep '02  
GeneralRe: how to change .bmp files to .jpg files Pinmemberraygall14:15 25 Dec '02  
GeneralRe: how to change .bmp files to .jpg files Pinsusskaorukamiya6:47 6 Jun '03  
Generalchanging JPEG files in .gif files PinmemberBellinger2:23 8 Jun '02  
GeneralResource leak! PinmemberAnonymous21:56 28 Oct '01  
GeneralDisplay & Edit Bitmap ? PinmemberAn Binh5:12 24 Sep '01  
GeneralRe: Display & Edit Bitmap ? PinmemberkimVong9:09 11 Oct '01  
GeneralRe: Display & Edit Bitmap ? PinmemberAnonymous16:17 11 Oct '01  
GeneralSimpler and easier way! PinmemberJarek Gibek4:05 7 Sep '01  
GeneralRe: Simpler and easier way! PinmemberAnonymous21:13 11 Apr '02  
GeneralRe: Simpler and easier way! PinsussWilfried Soeker10:52 16 Jul '04  
GeneralRe: Simpler and easier way! PinsussAnonymous13:03 20 Oct '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Sep 2000
Editor: Chris Maunder
Copyright 2000 by Wes Rogers
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project