dib.cpp

来自「A*算法 A*算法 A*算法 A*算法A*算法A*算法」· C++ 代码 · 共 804 行 · 第 1/2 页

CPP
804
字号
///////////////////////////////////////////////////////////////////////////////
// Name:        src/msw/dib.cpp
// Purpose:     implements wxDIB class
// Author:      Vadim Zeitlin
// Modified by:
// Created:     03.03.03 (replaces the old file with the same name)
// RCS-ID:      $Id: dib.cpp,v 1.63 2005/07/29 11:17:28 VZ Exp $
// Copyright:   (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
// License:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

/*
    TODO: support for palettes is very incomplete, several functions simply
          ignore them (we should select and realize the palette, if any, before
          caling GetDIBits() in the DC we use with it.
 */

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#ifndef WX_PRECOMP
    #include "wx/string.h"
    #include "wx/log.h"
#endif //WX_PRECOMP

#if wxUSE_WXDIB

#include "wx/bitmap.h"
#include "wx/intl.h"
#include "wx/file.h"

#include <stdio.h>
#include <stdlib.h>

#if !defined(__MWERKS__) && !defined(__SALFORDC__)
    #include <memory.h>
#endif

#include "wx/image.h"
#include "wx/msw/dib.h"

#ifdef __WXWINCE__
    #include <shellapi.h>       // for SHLoadDIBitmap()
#endif

// ----------------------------------------------------------------------------
// private functions
// ----------------------------------------------------------------------------

// calculate the number of palette entries needed for the bitmap with this
// number of bits per pixel
static inline WORD GetNumberOfColours(WORD bitsPerPixel)
{
    // only 1, 4 and 8bpp bitmaps use palettes (well, they could be used with
    // 24bpp ones too but we don't support this as I think it's quite uncommon)
    return (WORD)(bitsPerPixel <= 8 ? 1 << bitsPerPixel : 0);
}

// wrapper around ::GetObject() for DIB sections
static inline bool GetDIBSection(HBITMAP hbmp, DIBSECTION *ds)
{
    // note that at least under Win9x (this doesn't seem to happen under Win2K
    // but this doesn't mean anything, of course), GetObject() may return
    // sizeof(DIBSECTION) for a bitmap which is *not* a DIB section and the way
    // to check for it is by looking at the bits pointer
    return ::GetObject(hbmp, sizeof(DIBSECTION), ds) == sizeof(DIBSECTION) &&
                ds->dsBm.bmBits;
}

// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// wxDIB creation
// ----------------------------------------------------------------------------

bool wxDIB::Create(int width, int height, int depth)
{
    // we don't support formats using palettes right now so we only create
    // either 24bpp (RGB) or 32bpp (RGBA) bitmaps
    wxASSERT_MSG( depth, _T("invalid image depth in wxDIB::Create()") );
    if ( depth < 24 )
        depth = 24;

    // allocate memory for bitmap structures
    static const int sizeHeader = sizeof(BITMAPINFOHEADER);

    BITMAPINFO *info = (BITMAPINFO *)malloc(sizeHeader);
    wxCHECK_MSG( info, false, _T("malloc(BITMAPINFO) failed") );

    memset(info, 0, sizeHeader);

    info->bmiHeader.biSize = sizeHeader;
    info->bmiHeader.biWidth = width;

    // we use positive height here which corresponds to a DIB with normal, i.e.
    // bottom to top, order -- normally using negative height (which means
    // reversed for MS and hence natural for all the normal people top to
    // bottom line scan order) could be used to avoid the need for the image
    // reversal in Create(image) but this doesn't work under NT, only Win9x!
    info->bmiHeader.biHeight = height;

    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biBitCount = (WORD)depth;
    info->bmiHeader.biSizeImage = GetLineSize(width, depth)*height;

    m_handle = ::CreateDIBSection
                 (
                    0,              // hdc (unused with DIB_RGB_COLORS)
                    info,           // bitmap description
                    DIB_RGB_COLORS, // use RGB, not palette
                    &m_data,        // [out] DIB bits
                    NULL,           // don't use file mapping
                    0               // file mapping offset (not used here)
                 );

    free(info);

    if ( !m_handle )
    {
        wxLogLastError(wxT("CreateDIBSection"));

        return false;
    }

    m_width = width;
    m_height = height;
    m_depth = depth;

    return true;
}

bool wxDIB::Create(const wxBitmap& bmp)
{
    wxCHECK_MSG( bmp.Ok(), false, _T("wxDIB::Create(): invalid bitmap") );

    if ( !Create(GetHbitmapOf(bmp)) )
        return false;

    m_hasAlpha = bmp.HasAlpha();

    return true;
}

bool wxDIB::Create(HBITMAP hbmp)
{
    // this bitmap could already be a DIB section in which case we don't need
    // to convert it to DIB
    DIBSECTION ds;
    if ( GetDIBSection(hbmp, &ds) )
    {
        m_handle = hbmp;

        // wxBitmap will free it, not we
        m_ownsHandle = false;

        // copy all the bitmap parameters too as we have them now anyhow
        m_width = ds.dsBm.bmWidth;
        m_height = ds.dsBm.bmHeight;
        m_depth = ds.dsBm.bmBitsPixel;

        m_data = ds.dsBm.bmBits;
    }
    else // no, it's a DDB -- convert it to DIB
    {
        // prepare all the info we need
        BITMAP bm;
        if ( !::GetObject(hbmp, sizeof(bm), &bm) )
        {
            wxLogLastError(wxT("GetObject(bitmap)"));

            return false;
        }

        int d = bm.bmBitsPixel;
        if ( d <= 0 )
            d = wxDisplayDepth();

        if ( !Create(bm.bmWidth, bm.bmHeight, d) || !CopyFromDDB(hbmp) )
            return false;
    }

    return true;
}

// Windows CE doesn't have GetDIBits() so use an alternative implementation
// for it
//
// in fact I'm not sure if GetDIBits() is really much better than using
// BitBlt() like this -- it should be faster but I didn't do any tests, if
// anybody has time to do them and by chance finds that GetDIBits() is not
// much faster than BitBlt(), we could always use the Win CE version here
#ifdef __WXWINCE__

bool wxDIB::CopyFromDDB(HBITMAP hbmp)
{
    MemoryHDC hdcSrc;
    if ( !hdcSrc )
        return false;

    SelectInHDC selectSrc(hdcSrc, hbmp);
    if ( !selectSrc )
        return false;

    MemoryHDC hdcDst;
    if ( !hdcDst )
        return false;

    SelectInHDC selectDst(hdcDst, m_handle);
    if ( !selectDst )
        return false;


    if ( !::BitBlt(
                    hdcDst,
                    0, 0, m_width, m_height,
                    hdcSrc,
                    0, 0,
                    SRCCOPY
                  ) )
    {
        wxLogLastError(_T("BitBlt(DDB -> DIB)"));

        return false;
    }

    return true;
}

#else // !__WXWINCE__

bool wxDIB::CopyFromDDB(HBITMAP hbmp)
{
    DIBSECTION ds;
    if ( !GetDIBSection(m_handle, &ds) )
    {
        // we're sure that our handle is a DIB section, so this should work
        wxFAIL_MSG( _T("GetObject(DIBSECTION) unexpectedly failed") );

        return false;
    }

    if ( !::GetDIBits
            (
                ScreenHDC(),                // the DC to use
                hbmp,                       // the source DDB
                0,                          // first scan line
                m_height,                   // number of lines to copy
                ds.dsBm.bmBits,             // pointer to the buffer
                (BITMAPINFO *)&ds.dsBmih,   // bitmap header
                DIB_RGB_COLORS              // and not DIB_PAL_COLORS
            ) )
    {
        wxLogLastError(wxT("GetDIBits()"));

        return false;
    }

    return true;
}

#endif // __WXWINCE__/!__WXWINCE__

// ----------------------------------------------------------------------------
// Loading/saving the DIBs
// ----------------------------------------------------------------------------

bool wxDIB::Load(const wxString& filename)
{
#ifdef __WXWINCE__
    m_handle = SHLoadDIBitmap(filename);
#else // !__WXWINCE__
    m_handle = (HBITMAP)::LoadImage
                         (
                            wxGetInstance(),
                            filename,
                            IMAGE_BITMAP,
                            0, 0, // don't specify the size
                            LR_CREATEDIBSECTION | LR_LOADFROMFILE
                         );
#endif // __WXWINCE__

    if ( !m_handle )
    {
        wxLogLastError(_T("Loading DIB from file"));

        return false;
    }

    return true;
}

bool wxDIB::Save(const wxString& filename)
{
    wxCHECK_MSG( m_handle, false, _T("wxDIB::Save(): invalid object") );

    wxFile file(filename, wxFile::write);
    bool ok = file.IsOpened();
    if ( ok )
    {
        DIBSECTION ds;
        if ( !GetDIBSection(m_handle, &ds) )
        {
            wxLogLastError(_T("GetObject(hDIB)"));
        }
        else
        {
            BITMAPFILEHEADER bmpHdr;
            wxZeroMemory(bmpHdr);

            const size_t sizeHdr = ds.dsBmih.biSize;
            const size_t sizeImage = ds.dsBmih.biSizeImage;

            bmpHdr.bfType = 0x4d42;    // 'BM' in little endian
            bmpHdr.bfOffBits = sizeof(BITMAPFILEHEADER) + ds.dsBmih.biSize;
            bmpHdr.bfSize = bmpHdr.bfOffBits + sizeImage;

            // first write the file header, then the bitmap header and finally the
            // bitmap data itself
            ok = file.Write(&bmpHdr, sizeof(bmpHdr)) == sizeof(bmpHdr) &&
                    file.Write(&ds.dsBmih, sizeHdr) == sizeHdr &&
                        file.Write(ds.dsBm.bmBits, sizeImage) == sizeImage;
        }
    }

    if ( !ok )
    {
        wxLogError(_("Failed to save the bitmap image to file \"%s\"."),
                   filename.c_str());
    }

    return ok;
}

// ----------------------------------------------------------------------------
// wxDIB accessors
// ----------------------------------------------------------------------------

void wxDIB::DoGetObject() const
{
    // only do something if we have a valid DIB but we don't [yet] have valid
    // data
    if ( m_handle && !m_data )
    {
        // although all the info we need is in BITMAP and so we don't really
        // need DIBSECTION we still ask for it as modifying the bit values only
        // works for the real DIBs and not for the bitmaps and it's better to
        // check for this now rather than trying to find out why it doesn't
        // work later
        DIBSECTION ds;
        if ( !GetDIBSection(m_handle, &ds) )
        {
            wxLogLastError(_T("GetObject(hDIB)"));
            return;
        }

        wxDIB *self = wxConstCast(this, wxDIB);

        self->m_width = ds.dsBm.bmWidth;
        self->m_height = ds.dsBm.bmHeight;
        self->m_depth = ds.dsBm.bmBitsPixel;
        self->m_data = ds.dsBm.bmBits;
    }
}

// ----------------------------------------------------------------------------
// DDB <-> DIB conversions
// ----------------------------------------------------------------------------

#ifndef __WXWINCE__

HBITMAP wxDIB::CreateDDB(HDC hdc) const
{
    wxCHECK_MSG( m_handle, 0, _T("wxDIB::CreateDDB(): invalid object") );

    DIBSECTION ds;
    if ( !GetDIBSection(m_handle, &ds) )
    {
        wxLogLastError(_T("GetObject(hDIB)"));

        return 0;
    }

    // how many colours are we going to have in the palette?
    DWORD biClrUsed = ds.dsBmih.biClrUsed;
    if ( !biClrUsed )
    {
        // biClrUsed field might not be set
        biClrUsed = GetNumberOfColours(ds.dsBmih.biBitCount);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?