Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> загрузка файла в HBIMAP, Visual C++ 
:(
    Опции темы
pyro
Дата 23.11.2003, 16:04 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 23.11.2003

Репутация: нет
Всего: нет



omg.gif люди добрые, кто-нить знает, как по-человечески загрузить бээмпэшку в HBITMAP? Причём, желательно без MFC и ATL(CImage), используя только GDI?
PM MAIL   Вверх
DENNN
Дата 24.11.2003, 10:30 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 3878
Регистрация: 27.3.2002
Где: Москва

Репутация: 1
Всего: 43



WinAPI:
::LoadBitmap(......)
PM ICQ   Вверх
pyro
Дата 27.11.2003, 01:14 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 23.11.2003

Репутация: нет
Всего: нет



Цитата из MSDN: The LoadBitmap function loads the specified bitmap resource from a module's executable file.
Мне не надо её их ресурсов грузить, мне надо из ФАЙЛА!!! (*.bmp) baaa.gif
PM MAIL   Вверх
Ars
Дата 27.11.2003, 14:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 325
Регистрация: 28.8.2003
Где: Московская обл.

Репутация: 2
Всего: 2



В хелпе нашел, как сохранять. Попробуй по аналогии
Цитата
Many applications store images permanently as files. For example, drawing applications store pictures, spreadsheet applications store charts, CAD applications store drawings, and so on.

If you are writing an application that will store a bitmapped image in a file, you should use the Windows file format described in Bitmap Storage. In order to store a bitmap in this format, you must initialize a BITMAPINFO structure (consisting of a BITMAPFILEHEADER structure and an array of RGBQUAD structures), as well as an array of palette indices.
The following example code defines a function that allocates memory for and initializes members within a BITMAPINFOHEADER structure.

PBITMAPINFO CreateBitmapInfoStruct(HWND hwnd, HBITMAP hBmp) { 
    BITMAP bmp;
    PBITMAPINFO pbmi;
    WORD    cClrBits;

    /* Retrieve the bitmap's color format, width, and height. */

    if (!GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp))
        errhandler("GetObject", hwnd);


    /* Convert the color format to a count of bits. */

    cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);

    if (cClrBits == 1)
        cClrBits = 1;

    else if (cClrBits <= 4)
        cClrBits = 4;
    else if (cClrBits <= 8)
        cClrBits = 8;
    else if (cClrBits <= 16)
        cClrBits = 16;
    else if (cClrBits <= 24)
        cClrBits = 24;
    else
        cClrBits = 32;

    /*
    * Allocate memory for the BITMAPINFO structure. (This structure
    * contains a BITMAPINFOHEADER structure and an array of RGBQUAD data
    * structures.)
    */

    if (cClrBits != 24)
        pbmi = (PBITMAPINFO) LocalAlloc(LPTR,

                    sizeof(BITMAPINFOHEADER) +
                    sizeof(RGBQUAD) * (2^cClrBits));

    /*
    * There is no RGBQUAD array for the 24-bit-per-pixel format.
    */

    else
        pbmi = (PBITMAPINFO) LocalAlloc(LPTR,
                    sizeof(BITMAPINFOHEADER));



    /* Initialize the fields in the BITMAPINFO structure. */

    pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    pbmi->bmiHeader.biWidth = bmp.bmWidth;

    pbmi->bmiHeader.biHeight = bmp.bmHeight;
    pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
    pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
    if (cClrBits < 24)
        pbmi->bmiHeader.biClrUsed = 2^cClrBits;


    /* If the bitmap is not compressed, set the BI_RGB flag. */

    pbmi->bmiHeader.biCompression = BI_RGB;

    /*
    * Compute the number of bytes in the array of color
    * indices and store the result in biSizeImage.
    */


    pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) /8
                                  * pbmi->bmiHeader.biHeight
                                  * cClrBits;

    /*
    * Set biClrImportant to 0, indicating that all of the
    * device colors are important.
    */

    pbmi->bmiHeader.biClrImportant = 0;

    return pbmi;

}


The following example code defines a function that initializes the remaining structures, retrieves the array of palette indices, opens the file, copies the data, and closes the file.

void CreateBMPFile(HWND hwnd, LPTSTR pszFile, PBITMAPINFO pbi, 
                  HBITMAP hBMP, HDC hDC)
{

    HANDLE hf;                  /* file handle */
    BITMAPFILEHEADER hdr;      /* bitmap file-header */
    PBITMAPINFOHEADER pbih;    /* bitmap info-header */
    LPBYTE lpBits;              /* memory pointer */
    DWORD dwTotal;              /* total count of bytes */
    DWORD cb;                  /* incremental count of bytes */
    BYTE *hp;                  /* byte pointer */

    DWORD dwTmp;


    pbih = (PBITMAPINFOHEADER) pbi;
    lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);
    if (!lpBits)
        errhandler("GlobalAlloc", hwnd);

    /*
    * Retrieve the color table (RGBQUAD array) and the bits
    * (array of palette indices) from the DIB.
    */

    if (!GetDIBits(hDC, hBMP, 0, (WORD) pbih->biHeight,
                  lpBits, pbi, DIB_RGB_COLORS))
        errhandler("GetDIBits", hwnd);


    /* Create the .BMP file. */

    hf = CreateFile(pszFile,
                  GENERIC_READ | GENERIC_WRITE,
                  (DWORD) 0,
                  (LPSECURITY_ATTRIBUTES) NULL,
                  CREATE_ALWAYS,
                  FILE_ATTRIBUTE_NORMAL,
                  (HANDLE) NULL);

    if (hf == INVALID_HANDLE_VALUE)
        errhandler("CreateFile", hwnd);

    hdr.bfType = 0x4d42;        /* 0x42 = "B" 0x4d = "M" */

    /* Compute the size of the entire file. */


    hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) +
                pbih->biSize + pbih->biClrUsed
                * sizeof(RGBQUAD) + pbih->biSizeImage);

    hdr.bfReserved1 = 0;
    hdr.bfReserved2 = 0;

    /* Compute the offset to the array of color indices. */

    hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) +
                    pbih->biSize + pbih->biClrUsed
                    * sizeof (RGBQUAD);

    /* Copy the BITMAPFILEHEADER into the .BMP file. */


    if (!WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER),
      (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))
      errhandler("WriteFile", hwnd);

    /* Copy the BITMAPINFOHEADER and RGBQUAD array into the file. */

    if (!WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER)
                  + pbih->biClrUsed * sizeof (RGBQUAD),
                  (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))
      errhandler("WriteFile", hwnd);

    /* Copy the array of color indices into the .BMP file. */


    dwTotal = cb = pbih->biSizeImage;
    hp = lpBits;
    while (cb > MAXWRITE)  {
            if (!WriteFile(hf, (LPSTR) hp, (int) MAXWRITE,
                          (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))
                errhandler("WriteFile", hwnd);
            cb-= MAXWRITE;
            hp += MAXWRITE;
    }
    if (!WriteFile(hf, (LPSTR) hp, (int) cb,
        (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))
          errhandler("WriteFile", hwnd);


    /* Close the .BMP file. */

    if (!CloseHandle(hf))
          errhandler("CloseHandle", hwnd);

    /* Free memory. */

    GlobalFree((HGLOBAL)lpBits);
}



--------------------
Есть многое на свете, друг Горацио,
С чем очень долго можно прое..!
PM MAIL   Вверх
Madest
Дата 27.11.2003, 14:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 143
Регистрация: 27.11.2003
Где: Городок

Репутация: нет
Всего: нет



HANDLE LoadImage(
HINSTANCE hinst, //дескриптор приложения
LPCTSTR lpszName //имя файла или идентификатор
UINT uType, //тип изображения
int cxDesired, //щирина
int cyDesired, //высота
UINT fuLoad //флаги загрузки
);
uType на выбор:
IMAGE_BITMAP
IMAGE_CURSOR
IMAGE_ICON
Флагов много. Самые важные:
LR_LOADFROMFILE - тогда lpszName - имя файла, если флаг не установлен, lpszName- идентификатор
LR_DEFAULTCOLOR чтоб был цветной
Пример:
HBITMAP zezo=(HBITMAP)LoadImage(NULL,"zezo.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_DEFAULTCOLOR);
--------------------
PM MAIL   Вверх
DENNN
Дата 27.11.2003, 15:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 3878
Регистрация: 27.3.2002
Где: Москва

Репутация: 1
Всего: 43



Цитата
В хелпе нашел, как сохранять. Попробуй по аналогии

Если это хелп из мсдн к 6 студии, то пример не рабочий. sad.gif
PM ICQ   Вверх
Ars
Дата 27.11.2003, 15:56 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 325
Регистрация: 28.8.2003
Где: Московская обл.

Репутация: 2
Всего: 2



Цитата
Если это хелп из мсдн к 6 студии, то пример не рабочий.

Неважно, рабочий он или нет. Главное, дает представление о необходимых действиях.
А пример из Win32 Programmer's Reference, поставляемого с Билдером и слизанного, видимо, с мсдн


--------------------
Есть многое на свете, друг Горацио,
С чем очень долго можно прое..!
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.1276 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.