Форум программистов «Весельчак У»
  *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

  • Рекомендуем проверить настройки временной зоны в вашем профиле (страница "Внешний вид форума", пункт "Часовой пояс:").
  • У нас больше нет рассылок. Если вам приходят письма от наших бывших рассылок mail.ru и subscribe.ru, то знайте, что это не мы рассылаем.
   Начало  
Наши сайты
Помощь Поиск Календарь Почта Войти Регистрация  
 
Страниц: [1]   Вниз
  Печать  
Автор Тема: работа с bmp-ресурсами  (Прочитано 13337 раз)
0 Пользователей и 1 Гость смотрят эту тему.
binisio
Гость
« : 18-01-2005 11:00 » 

подскажите пожалуйста
1 как считать заголовочную и прочую информацию из bmp-файла, если он вложен в ресурсы? если, к примеру, загружать его с помощью LoadBitmap()
и еще
2  как осуществить блиттирг bmp-файла из ресурсов на поверхность DDraw? Как я понимаю есть два способа: один с помощью GDI и собственно средствами DDraw...
Записан
Finch
Спокойный
Администратор

il
Offline Offline
Пол: Мужской
Пролетал мимо


« Ответ #1 : 18-01-2005 20:02 » 

1. Когда ты скачал из ресурса битмап при помоши функции LoadBitmap, ты получаеш описатель его HBITMAP. Затем при помоши функции
Цитата
The GetObject function obtains information about a specified graphics object. Depending on the graphics object, the function places a filled-in BITMAP, DIBSECTION, EXTLOGPEN, LOGBRUSH, LOGFONT, or LOGPEN structure, or a count of table entries (for a logical palette), into a specified buffer.

int GetObject(

    HGDIOBJ hgdiobj,   // handle to graphics object of interest
    int cbBuffer,   // size of buffer for object information
    LPVOID lpvObject    // pointer to buffer for object information 
   );   
 

Parameters

hgdiobj

A handle to the graphics object of interest. This can be a handle to one of the following: a logical bitmap, a brush, a font, a palette, a pen, or a device independent bitmap created by calling the CreateDIBSection function.

cbBuffer

Specifies the number of bytes of information to be written to the buffer.

lpvObject

Points to a buffer that is to receive the information about the specified graphics object.
The following table shows the type of information the buffer receives for each type of graphics object you can specify with hgdiobj:

 

hgdiobj Type   Data Written to *lpvObject
HBITMAP   BITMAP
HBITMAP returned from a call to CreateDIBSection   DIBSECTION, if cbBuffer is set to sizeof(DIBSECTION), or BITMAP, if cbBuffer is set to sizeof(BITMAP)
HPALETTE   a WORD count of the number of entries in the logical palette
HPEN returned from a call to ExtCreatePen   EXTLOGPEN
HPEN   LOGPEN
HBRUSH   LOGBRUSH
HFONT   LOGFONT
 

If the lpvObject parameter is NULL, the function return value is the number of bytes required to store the information it writes to the buffer for the specified graphics object.

 

Return Values

If the function succeeds, and lpvObject is a valid pointer, the return value is the number of bytes stored into the buffer.
If the function succeeds, and lpvObject is NULL, the return value is the number of bytes required to hold the information the function would store into the buffer.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The buffer pointed to by the lpvObject parameter must be sufficiently large to receive the information about the graphics object.
If hgdiobj identifies a bitmap created by calling CreateDIBSection, and the specified buffer is large enough, the GetObject function returns a DIBSECTION structure. In addition, the bmBits member of the BITMAP structure contained within the DIBSECTION will contain a pointer to the bitmap's bit values.

If hgdiobj identifies a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.
If hgdiobj identifies a logical palette, GetObject retrieves a two-byte integer that specifies the number of entries in the palette. The function does not retrieve the LOGPALETTE structure defining the palette. To retrieve information about palette entries, an application can call the GetPaletteEntries function.
ты получиш структуру BITMAP,
Цитата
The BITMAP structure defines the type, width, height, color format, and bit values of a bitmap.

typedef struct tagBITMAP {  // bm 
   LONG   bmType;
   LONG   bmWidth;
   LONG   bmHeight;
   LONG   bmWidthBytes;
   WORD   bmPlanes;
   WORD   bmBitsPixel;
   LPVOID bmBits;
} BITMAP;
 

Members

bmType

Specifies the bitmap type. This member must be zero.

bmWidth

Specifies the width, in pixels, of the bitmap. The width must be greater than zero.

bmHeight

Specifies the height, in pixels, of the bitmap. The height must be greater than zero.

bmWidthBytes

Specifies the number of bytes in each scan line. This value must be divisible by 2, because Windows assumes that the bit values of a bitmap form an array that is word aligned.

bmPlanes

Specifies the count of color planes.

bmBitsPixel

Specifies the number of bits required to indicate the color of a pixel.

bmBits

Points to the location of the bit values for the bitmap. The bmBits member must be a long pointer to an array of character (1-byte) values.

 

Remarks

The bitmap formats currently used are monochrome and color. The monochrome bitmap uses a one-bit, one-plane format. Each scan is a multiple of 32 bits.
Scans are organized as follows for a monochrome bitmap of height n:

    Scan 0 
    Scan 1
    .
    .
    .
    Scan n-2
    Scan n-1
 

The pixels on a monochrome device are either black or white. If the corresponding bit in the bitmap is 1, the pixel is set to the foreground color; if the corresponding bit in the bitmap is zero, the pixel is set to the background color.
All devices that have the RC_BITBLT device capability support bitmaps. For more information, see GetDeviceCaps.
Each device has a unique color format. To transfer a bitmap from one device to another, use the GetDIBits and SetDIBits functions.

2. Принцип прорисовки Битмапа в WinAPI очень простой. Сначало создается подобный совместимый дескриптор окна при помоши функции
Цитата
The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device.

HDC CreateCompatibleDC(

    HDC hdc    // handle to memory device context
   );   
 

Parameters

hdc

Identifies the device context. If this handle is NULL, the function creates a memory device context compatible with the application's current screen.

 

Return Values

If the function succeeds, the return value is the handle to a memory device context.
If the function fails, the return value is NULL.

Remarks

Before an application can use a memory device context for drawing operations, it must select a bitmap of the correct width and height into the device context. Once a bitmap has been selected, the device context can be used to prepare images that will be copied to the screen or printed.
The CreateCompatibleDC function can only be used with devices that support raster operations. An application can determine whether a device supports these operations by calling the GetDeviceCaps function.

When you no longer need the memory device context, call the DeleteDC function to delete it.
Затем заменяется у совместимого дескриптора Битмап твоим Битмапом при помоши функции
Цитата
The SelectObject function selects an object into the specified device context. The new object replaces the previous object of the same type.

HGDIOBJ SelectObject(

    HDC hdc,   // handle of device context
    HGDIOBJ hgdiobj    // handle of object 
   );   
 

Parameters

hdc

Identifies the device context.

hgdiobj

Identifies the object to be selected. The specified object must have been created by using one of the following functions:

Object   Functions
Bitmap   CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBSection
(Bitmaps can be selected for memory device contexts only, and for only one device context at a time.)
Brush   CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush
Font   CreateFont, CreateFontIndirect
Pen   CreatePen, CreatePenIndirect
Region   CombineRgn, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect
 

Return Values

If the selected object is not a region and the function succeeds, the return value is the handle of the object being replaced. If the selected object is a region and the function succeeds, the return value is one of the following values:

Value   Meaning
SIMPLEREGION   Region consists of a single rectangle.
COMPLEXREGION   Region consists of more than one rectangle.
NULLREGION   Region is empty.
 

If an error occurs and the selected object is not a region, the return value is NULL. Otherwise, it is GDI_ERROR.

Remarks

This function returns the previously selected object of the specified type. An application should always replace a new object with the original, default object after it has finished drawing with the new object.
An application cannot select a bitmap into more than one device context at a time.
Производиш прорисовку с совместимого дескриптора в твой дескриптор окна при помоши функции
Цитата
The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.

BOOL BitBlt(

    HDC hdcDest,   // handle to destination device context
    int nXDest,   // x-coordinate of destination rectangle's upper-left corner
    int nYDest,   // y-coordinate of destination rectangle's upper-left corner
    int nWidth,   // width of destination rectangle
    int nHeight,   // height of destination rectangle
    HDC hdcSrc,   // handle to source device context
    int nXSrc,   // x-coordinate of source rectangle's upper-left corner 
    int nYSrc,   // y-coordinate of source rectangle's upper-left corner
    DWORD dwRop    // raster operation code
   );   
 

Parameters

hdcDest

Identifies the destination device context.

nXDest

Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

nYDest

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth

Specifies the logical width of the source and destination rectangles.

nHeight

Specifies the logical height of the source and the destination rectangles.

hdcSrc

Identifies the source device context.

nXSrc

Specifies the logical x-coordinate of the upper-left corner of the source rectangle.

nYSrc

Specifies the logical y-coordinate of the upper-left corner of the source rectangle.

dwRop

Specifies a raster-operation code. These codes define how the color data for the source rectangle is to be combined with the color data for the destination rectangle to achieve the final color.
The following list shows some common raster operation codes:

Value   Description
BLACKNESS   Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the default physical palette.)
DSTINVERT   Inverts the destination rectangle.
MERGECOPY   Merges the colors of the source rectangle with the specified pattern by using the Boolean AND operator.
MERGEPAINT   Merges the colors of the inverted source rectangle with the colors of the destination rectangle by using the Boolean OR operator.
NOTSRCCOPY   Copies the inverted source rectangle to the destination.
NOTSRCERASE   Combines the colors of the source and destination rectangles by using the Boolean OR operator and then inverts the resultant color.
PATCOPY   Copies the specified pattern into the destination bitmap.
PATINVERT   Combines the colors of the specified pattern with the colors of the destination rectangle by using the Boolean XOR operator.
PATPAINT   Combines the colors of the pattern with the colors of the inverted source rectangle by using the Boolean OR operator. The result of this operation is combined with the colors of the destination rectangle by using the Boolean OR operator.
SRCAND   Combines the colors of the source and destination rectangles by using the Boolean AND operator.
SRCCOPY   Copies the source rectangle directly to the destination rectangle.
SRCERASE   Combines the inverted colors of the destination rectangle with the colors of the source rectangle by using the Boolean AND operator.
SRCINVERT   Combines the colors of the source and destination rectangles by using the Boolean XOR operator.
SRCPAINT   Combines the colors of the source and destination rectangles by using the Boolean OR operator.
WHITENESS   Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the default physical palette.)
 

Return Values

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

Remarks

If a rotation or shear transformation is in effect in the source device context, BitBlt returns an error. If other transformations exist in the source device context (and a matching transformation is not in effect in the destination device context), the rectangle in the destination device context is stretched, compressed, or rotated as necessary.
If the color formats of the source and destination device contexts do not match, the BitBlt function converts the source color format to match the destination format.

When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.
Not all devices support the BitBlt function. For more information, see the RC_BITBLT raster capability entry in GetDeviceCaps.
BitBlt returns an error if the source and destination device contexts represent different devices.

Пример:
HBITMAP hbm = LoadBitmap(..........);
HDC dcc=CreateCompatibleDC(DC);
HBITMAP obm=SelectObject(dcc, hbm);
BitBlt(DC, 0, 0, 100, 100, dcc, 0, 0, SRCCOPY);
SelectObject(dcc, obm);
DeleteDC(dcc);

« Последнее редактирование: 20-12-2007 20:41 от Алексей1153++ » Записан

Не будите спашяго дракона.
             Джаффар (Коша)
binisio
Гость
« Ответ #2 : 19-01-2005 09:28 » 

Finch - СПАСИБО!
только компилятор ругается на
HBITMAP obm=SelectObject(dcc, hbm);
я изменил
HANDLE bmp=SelectObject(dcc, obm);

кстати, честно говоря не понял, зачем вообще нужно сохранять в obm и вновь вызывать SelectObject в конце?

« Последнее редактирование: 19-01-2005 13:55 от binisio » Записан
Finch
Спокойный
Администратор

il
Offline Offline
Пол: Мужской
Пролетал мимо


« Ответ #3 : 19-01-2005 19:16 » 

Binisio дискриптор окна это комплекс объектов таких как Битмап, фонт, кисть, карандаш, регион. Как правило когда создаётся дескриптор окна, все перечисленные объекты устанавливаются по умолчанию. Когда ты уничтожаеш дескриптор. Автоматически уменьшается счетчик использования объектов. Хотя сохраненный битмап и нулевой. Но его описатели занимают память. Чтобы не было утечки памяти применяется такая схема.

В принципе HBITMAP и HANDLE описаны как DWORD. Но компилятор может считать их разными типами. Нужно приведение типов.
HBITMAP obm=(HBITMAP) SelectObject(dcc, hbm);
Записан

Не будите спашяго дракона.
             Джаффар (Коша)
binisio
Гость
« Ответ #4 : 20-01-2005 10:40 » 

Finch еще раз спасибо!
Все получилось, вернее не совсем все. Не получается передать битмапку из ресурсов на поверхность DirectDraw.
Я сохраняю в HDC DC контекст поверхности  DirectDraw c помощью lpdds->GetDC().
Пытаюсь с помощью BitBlt() - не получается.

Потом, нашел в папке DXSDK\samples\С++\common\include нашел файлик ddutil.cpp, а в нем такую функцию

//-----------------------------------------------------------------------------
// Name: CSurface::DrawBitmap()
// Desc: Draws a bitmap over an entire DirectDrawSurface, stretching the
//       bitmap if nessasary
//-----------------------------------------------------------------------------
HRESULT CSurface::DrawBitmap( HBITMAP hBMP,
                              DWORD dwBMPOriginX, DWORD dwBMPOriginY,
                              DWORD dwBMPWidth, DWORD dwBMPHeight )
{
    HDC            hDCImage;
    HDC            hDC;
    BITMAP         bmp;
    DDSURFACEDESC2 ddsd;
    HRESULT        hr;

    if( hBMP == NULL || m_pdds == NULL )
        return E_INVALIDARG;

    // Make sure this surface is restored.
    if( FAILED( hr = m_pdds->Restore() ) )
        return hr;

    // Get the surface.description
    ddsd.dwSize  = sizeof(ddsd);
    m_pdds->GetSurfaceDesc( &ddsd );

    if( ddsd.ddpfPixelFormat.dwFlags == DDPF_FOURCC )
        return E_NOTIMPL;

    // Select bitmap into a memoryDC so we can use it.
    hDCImage = CreateCompatibleDC( NULL );
    if( NULL == hDCImage )
        return E_FAIL;

    SelectObject( hDCImage, hBMP );

    // Get size of the bitmap
    GetObject( hBMP, sizeof(bmp), &bmp );

    // Use the passed size, unless zero
    dwBMPWidth  = ( dwBMPWidth  == 0 ) ? bmp.bmWidth  : dwBMPWidth;     
    dwBMPHeight = ( dwBMPHeight == 0 ) ? bmp.bmHeight : dwBMPHeight;

    // Stretch the bitmap to cover this surface
    if( FAILED( hr = m_pdds->GetDC( &hDC ) ) )
        return hr;

    StretchBlt( hDC, 0, 0,
                ddsd.dwWidth, ddsd.dwHeight,
                hDCImage, dwBMPOriginX, dwBMPOriginY,
                dwBMPWidth, dwBMPHeight, SRCCOPY );

    if( FAILED( hr = m_pdds->ReleaseDC( hDC ) ) )
        return hr;

    DeleteDC( hDCImage );

    return S_OK;
}

___________________________________________________

в принципе все то же только используется StretchBlt(), но у меня опять ничего не получилось.
Записан
binisio
Гость
« Ответ #5 : 20-01-2005 11:56 » 

получилось!!!

вот такой код:


HBITMAP         hBMP;   
HDC            hDCImage;
HDC            hDC;
BITMAP         bmp;
DDSURFACEDESC2   ddsd;
LPDIRECTDRAWSURFACE7 buffer;

hBMP = (HBITMAP) LoadImage( GetModuleHandle(NULL), MAKEINTRESOURCE(101),
                                IMAGE_BITMAP, 640, 480,
                                LR_CREATEDIBSECTION );

GetObject( hBMP, sizeof(bmp), &bmp );

ZeroMemory( &ddsd, sizeof(ddsd) );
ddsd.dwSize         = sizeof(ddsd);
ddsd.dwFlags        = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth        = bmp.bmWidth;
ddsd.dwHeight       = bmp.bmHeight;

lpdd7->CreateSurface(&ddsd, &buffer, NULL);

hDCImage = CreateCompatibleDC( NULL );
SelectObject( hDCImage, hBMP );

GetObject( hBMP, sizeof(bmp), &bmp );

DWORD dwBMPWidth  = bmp.bmWidth;     
DWORD dwBMPHeight = bmp.bmHeight;

buffer->GetDC( &hDC );

StretchBlt( hDC, 0, 0,
                dwBMPWidth, dwBMPHeight,
                hDCImage, 100, 100,
                dwBMPWidth, dwBMPHeight, SRCCOPY );

buffer->ReleaseDC( hDC );

DeleteDC( hDCImage );

RECT source_rect, dest_rect;

source_rect.left=0;
source_rect.top=0;
source_rect.right=300;
source_rect.bottom=300;

dest_rect.left=0;
dest_rect.top=0;
dest_rect.right=300;
dest_rect.bottom=300;

lpdds->Blt(&dest_rect, buffer,
      &source_rect, DDBLT_WAIT, NULL);
Записан
binisio
Гость
« Ответ #6 : 20-01-2005 12:05 » 

а вот как сделать это не используя GDI?
Записан
Mfcer__
Команда клуба

ru
Offline Offline

« Ответ #7 : 24-01-2005 05:44 » 

а вот как сделать это не используя GDI?

Можно ипсользовать GDI+
Записан
binisio
Гость
« Ответ #8 : 24-01-2005 12:34 » 

а вот как сделать это не используя GDI?

Можно ипсользовать GDI+

а что это? и какое в этом случае  будет отличие от GDI?
Записан
Гром
Птычк. Тьфу, птычник... Вот!
Готовлюсь к пенсии

il
Offline Offline
Пол: Мужской
Бодрый птах


« Ответ #9 : 24-01-2005 21:27 » 

Без GDI можно сделать самому - хидер битмапы достаточно прост - формат известен и опубликован - сам напиши функцию которая будет раскрывать структуру битмапки.
У меня есть для частных случаев - валяется где то... Если надо могу выложить куски на обозрение.
Записан

А птичку нашу прошу не обижать!!!
binisio
Гость
« Ответ #10 : 25-01-2005 08:51 » 

Без GDI можно сделать самому - хидер битмапы достаточно прост - формат известен и опубликован - сам напиши функцию которая будет раскрывать структуру битмапки.
У меня есть для частных случаев - валяется где то... Если надо могу выложить куски на обозрение.

выкладывай!
насчет без GDI - просто я думал, что в DDraw есть для этого какая-нибудь функция
Записан
Страниц: [1]   Вверх
  Печать  
 

Powered by SMF 1.1.21 | SMF © 2015, Simple Machines