C++儲存BItmap、Jpg、png等圖片的方法
阿新 • • 發佈:2018-12-09
1.擁有RGB資料直接將資料寫出為.bmp檔案
void Save_bmp(const vector<char>& data) { BITMAPFILEHEADER bmfHdr; BITMAPINFOHEADER bi; const int count = 4; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = 1920; bi.biHeight = 1200; bi.biPlanes = 1; bi.biBitCount = count*8; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrImportant = 0; bi.biClrUsed = 0; auto biBitCount = count * 8; auto dwBmBitsSize = ((1920 * biBitCount + biBitCount-1) / biBitCount) * count * 1200; auto dwPaletteSize = 0; bmfHdr.bfType = 0x4D42; // "BM" auto dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize dwBmBitsSize; bmfHdr.bfSize = dwDIBSize; bmfHdr.bfReserved1 = 0; bmfHdr.bfReserved2 = 0; bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) dwPaletteSize; //建立點陣圖檔案 auto fh = CreateFile(L"c:\\test.bmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (fh == INVALID_HANDLE_VALUE) return ; DWORD dwWritten = 0; // 寫入點陣圖檔案頭 WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL); // 寫入點陣圖檔案其餘內容 WriteFile(fh, (LPSTR)&bi, sizeof(bi), &dwWritten, NULL); WriteFile(fh, (LPSTR)&data[0], data.size(), &dwWritten, NULL); CloseHandle(fh); }
2.DXD方式(需要包含標頭檔案#include <d3dx9tex.h>)
函式如下:
std::wstringstream Nub; Nub << i % 1024; std::wstring strnub = Nub.str(); //_T("image/png") , _T("image/bmp"), _T("image/gif"), _T("image/jpeg"), _T("image/tiff") std::wstring strSaveBmp = _T("c:\\ImageFiles\\DX\\bkDX"); strSaveBmp += strnub; strSaveBmp += _T(".png"); m_hr = D3DXSaveSurfaceToFile(strSaveBmp.c_str(), D3DXIFF_PNG, m_surf, NULL, &rect);
3.Gdiplus方式(需要包含標頭檔案#include <d3d9h>)
HBITMAP _BitmapInfo = objCapw->m_hDib; GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Gdiplus::Bitmap* m_pBackGroundBmp = Gdiplus::Bitmap::FromHBITMAP(_BitmapInfo, NULL); std::wstringstream Nub; Nub << i % 1024; std::wstring strnub = Nub.str(); _T("image/png") , _T("image/bmp"), _T("image/gif"), _T("image/jpeg"), _T("image/tiff") CLSID BmpClsid; GetEncoderClsid(_T("image/png"), &BmpClsid); std::wstring m_strSaveBmp = _T("e:\\ImageFiles\\GDI\\bkGDI"); m_strSaveBmp += strnub; m_strSaveBmp += _T(".png"); if (m_pBackGroundBmp) { m_pBackGroundBmp->Save(m_strSaveBmp.c_str(), &BmpClsid); } else { int det = 0; }