I've setup a PNG resource file in my SDL2 project for Windows 32bit in C++.
HRSRC hRes = FindResource(0, MAKEINTRESOURCE(IMGID), "PNG");
if (!hRes) {
Log::Error("Find resource IMGID");
return;
}
HGLOBAL hData = LoadResource(0, hRes);
if (!hData) {
Log::Error("Load resource IMGID");
return;
}
DWORD dataSize = SizeofResource(0, hRes);
char* data = (char*)LockResource(hData);
std::string result;
result.assign(data, dataSize);
The result variable contains all the characters of the PNG image (if it was converted to a string).
How can I use this image string with SDL Image and display it on the window?
Use SDL_RWFromConstMem(data, dataSize) to create a read-only memory-targeted SDL_RWops and pass that in to IMG_Load_RW().
Related
I have a project in Code::Blocks.
In my resource.rc file I have
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#define TWEETY 102
In my resource.h file I have
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include "resource.h"
TWEETY IMAGE "Tweety.png"
I build the project and afterwards open the exe file in ResEdit.
This is what I see there.
ResEdit
There are no resource names, only resource ids.
This has a consequence (at least it's my conclusion) that I cannot find the image resource using FindResource function.
// Loads the PNG containing the splash image into a HBITMAP.
HBITMAP LoadSplashImage()
{
HBITMAP hbmpSplash = NULL;
// load the PNG image data into a stream
IStream * ipImageStream = CreateStreamOnResource(MAKEINTRESOURCE(TWEETY), _T("PNG"));
if (ipImageStream == NULL)
goto Return;
// load the bitmap with WIC
IWICBitmapSource * ipBitmap = LoadBitmapFromStream(ipImageStream);
if (ipBitmap == NULL)
goto ReleaseStream;
// create a HBITMAP containing the image
hbmpSplash = CreateHBITMAP(ipBitmap);
ipBitmap->Release();
ReleaseStream:
ipImageStream->Release();
Return:
return hbmpSplash;
}
// Creates a stream object initialized with the data from an executable resource.
IStream * CreateStreamOnResource(LPCTSTR lpName, LPCTSTR lpType)
{
// initialize return value
IStream * ipStream = NULL;
// find the resource
HRSRC hrsrc = FindResource(NULL, lpName, lpType);
if (hrsrc == NULL)
goto Return;
// load the resource
DWORD dwResourceSize = SizeofResource(NULL, hrsrc);
HGLOBAL hglbImage = LoadResource(NULL, hrsrc);
if (hglbImage == NULL)
goto Return;
// lock the resource, getting a pointer to its data
LPVOID pvSourceResourceData = LockResource(hglbImage);
if (pvSourceResourceData == NULL)
goto Return;
// allocate memory to hold the resource data
HGLOBAL hgblResourceData = GlobalAlloc(GMEM_MOVEABLE, dwResourceSize);
if (hgblResourceData == NULL)
goto Return;
// get a pointer to the allocated memory
LPVOID pvResourceData = GlobalLock(hgblResourceData);
if (pvResourceData == NULL)
goto FreeData;
// copy the data from the resource to the new memory block
CopyMemory(pvResourceData, pvSourceResourceData, dwResourceSize);
GlobalUnlock(hgblResourceData);
// create a stream on the HGLOBAL containing the data
if (SUCCEEDED(CreateStreamOnHGlobal(hgblResourceData, TRUE, &ipStream)))
goto Return;
FreeData:
// couldn't create stream; free the memory
GlobalFree(hgblResourceData);
Return:
return ipStream;
}
Please advise what I'm doing wrong.
Update - it is working now.
TWEETY IMAGE "Tweety.png"
IStream * ipImageStream = CreateStreamOnResource(MAKEINTRESOURCE(TWEETY), _T("IMAGE"));
HRSRC hrsrc = FindResource(NULL, lpName, lpType);
However, in ResEdit I still don't see the resource name, only resource id.
And this:
MAKEINTRESOURCE(TWEETY);
returns "error - cannot access memory at address 0x66".
Resource types are identified by ID or name. Your resource script defines a resource type with name IMAGE (that's why you see "IMAGE" in ResEdit; note the quotation marks).
You are passing a resource type with name PNG to the call to FindResource. The module doesn't have a resource type named PNG. It contains a resource type named IMAGE. When you pass _T("IMAGE") your code starts to work.
I am trying to load in a BMP image from a resources folder into a QPixmap object. However, I can't read the bytes even though rewriting those bytes to a new file makes a correct copy of the original. Here is my loading method:
QPixmap* GUIMain::loadImage(int name) {
// Resource loading, works fine
HRSRC rc = FindResource(NULL, MAKEINTRESOURCE(name), RT_BITMAP);
if (rc == NULL) {
printf("INVALID RESOURCE ADDRESS (%i)\n", name);
return new QPixmap();
}
HGLOBAL rcData = LoadResource(NULL, rc);
LPVOID data = LockResource(rcData);
DWORD data_size = SizeofResource(NULL, rc);
// Rewrite file to new file, works fine
ofstream output("E:\\" + to_string(name) + ".bmp", std::ios::binary);
BITMAPFILEHEADER bfh = { 'MB', 54 + data_size, 0, 0, 54 };
output.write((char*)&bfh, sizeof(bfh));
output.write((char*)data, data_size);
output.close();
// Need to return, can't get bytes working
return new QPixmap(/*?*/);
}
This method is called with the definitions from the resource.h file.
I have tried to use a stringstream with the same calls as the ofstream, followed by using that stream as a source for the QPixmap, but the stream didn't produce the same output.
Here are the relevant parts of my resource.h file:
#define IDB_BITMAP1 101
#define IDB_BITMAP2 102
Here is my Resource.rc file:
IDB_BITMAP1 BITMAP "E:\\Downloads\\onIcon.bmp"
IDB_BITMAP2 BITMAP "E:\\Downloads\\offIcon.bmp"
I know I should be using the Qt tools for resource management, but I don't have the capabilities to do so.
You can use QPixmap::loadFromData(...) to create a QPixmap from bytes in bmp format, but you also need to not declare the resource as "BITMAP" in the .rc file.
Bitmap resources are intended to be used with LoadBitmap(...) or LoadImage(...) and are stored in the .exe with the bitmap header stripped off. (Raymond Chen discusses this here) Since you are not using LoadBitmap set the type of the resources to be arbitrary binary data, e.g.
IDB_BITMAP1 RCDATA "E:\\Downloads\\onIcon.bmp"
and then implement your image loading routine as below:
QPixmap* GUIMain::loadImage(int name) {
// ...
HGLOBAL rcData = LoadResource(NULL, rc);
LPVOID data = LockResource(rcData);
DWORD data_size = SizeofResource(NULL, rc);
QPixmap* pm = new QPixmap();
pm->loadFromData( static_cast<uchar*>(data), data_size, "bmp");
return pm;
}
I'm making a window c++ with winapi(non-MFC) and showing gif. For this Im using GDI++. I'm loading a gif to GDI::Image from the path, but I want to load it from resources. How can I do it?
hMWDC = GetDC(hWnd);
pGphcs = new Graphics(hMWDC);
WCHAR path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
PathRemoveFileSpecW(path);
PathAppendW(path, L"gifs\\test.gif");
pImg = new Image(path);
if (pImg) {
nFrmCnt = pImg->GetFrameCount(&FrameDimensionTime);
SetTimer(hWnd, DRAW_ANIM, 100, NULL);
}
case WM_TIMER:
if (wParam == DRAW_ANIM)
{
pImg->SelectActiveFrame(&FrameDimensionTime, nFrm);
Rect DRC(0, 0, pImg->GetWidth(), pImg->GetHeight());
pGphcs->Clear(Color(128, 128, 128));
pGphcs->DrawImage(pImg, DRC);
if (nFrm < (nFrmCnt - 1)) nFrm++; else nFrm = 0;
}
break;
There is an Image constructor that accepts an IStream*.
You can create a stream by calling SHCreateMemStream on the raw buffer of a resource, which can be obtained by calling FindResource/LoadResource/LockResource and SizeOfResource.
Add the GIF file to your app's resources at compile time. For instance, by compiling an .rc file similar to below into a .res file that you can then link into your executable (some compilers/IDEs have tools to automate this step):
Resources.rh
#define MY_GIF_ID 100
Resources.rc
#include "Resources.rh"
MY_GIF_ID RCDATA "gifs\\test.gif"
Then, you can obtain a pointer to the raw bytes of the resource at runtime.
#include "Resources.rh"
HMODULE hMod = GetModuleHandle(NULL);
HRSRC hRes = FindResource(hMod, MAKEINTRESOURCE(MY_GIF_ID), RT_RCDATA);
if (!hRes) { ... error handling ... }
HGLOBAL hGlobal = LoadResource(hMod, hRes);
if (!hGlobal) { ... error handling ... }
void *pResData = LockResource(hGlobal);
if (!pResData) { ... error handling ... }
DWORD dwResData = SizeofResource(hMod, hRes);
See MSDN for more details:
Introduction to Resources
Finding and Loading Resources
And then finally, pass the resource bytes to the Image constructor that takes an IStream* as input:
#include <shlwapi.h>
IStream *pStream = SHCreateMemStream((BYTE*)pResData, dwResData);
if (!pStream) { ... error handling ... }
pImg = new Image(pStream);
pStream->Release();
I'm working with some pictures in a MFC application, and I realized that the CImage class (from MFC) has 2 types of save, to a file and to a IStream interface. I'm trying to use that IStream interface to save to memory, using the convention features of the CImage class without another library to do that (for example bmp to jpg convertion). I don't want to save a file, just work with the memory buffers. The CImage object is already loaded with a picture file.
But I'm not able to use this IStream interface because I cannot create a object from that class and not realized how to create the buffer to use with that Save(IStream * pStream...) feature.
Any example will be very helpful.
Thanks,
Vitor
First, you should add your picture to a resource id, and to do like this:
BOOL ImageFromIDResource(UINT nID, LPCTSTR sTR, CImage * & pImg)
{
HINSTANCE hInst = AfxGetResourceHandle();
HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(nID), sTR); // type
if (!hRsrc)
return FALSE;
// load resource into memory
DWORD len = SizeofResource(hInst, hRsrc);
BYTE* lpRsrc = (BYTE*)LoadResource(hInst, hRsrc);
if (!lpRsrc)
return FALSE;
// Allocate global memory on which to create stream
HGLOBAL m_hMem = GlobalAlloc(GMEM_FIXED, len);
BYTE* pmem = (BYTE*)GlobalLock(m_hMem);
memcpy(pmem, lpRsrc, len);
IStream* pstm = NULL;
CreateStreamOnHGlobal(m_hMem, FALSE, &pstm);
// load from stream
//pImg = Gdiplus::Image::FromStream(pstm);
pImg = new CImage();
pImg->Load(pstm);
DWORD err = GetLastError();
// free/release stuff
GlobalUnlock(m_hMem);
pstm->Release();
FreeResource(lpRsrc);
return TRUE;
}
I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer.
Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward.
The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down.
This first part is what I figured out in the other question
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// I have this decode function from elsewhere
std::string decodedImage = base64_decode(Base64EncodedImage);
// Allocate the space for the stream
DWORD imageSize = decodedImage.length();
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize);
LPVOID pImage = ::GlobalLock(hMem);
memcpy(pImage, decodedImage.c_str(), imageSize);
// Create the stream
IStream* pStream = NULL;
::CreateStreamOnHGlobal(hMem, FALSE, &pStream);
// Create the image from the stream
Image image(pStream);
// Cleanup
pStream->Release();
GlobalUnlock(hMem);
GlobalFree(hMem);
(Base64 code)
And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done.
// Perform operation (rotate)
image.RotateFlip(Gdiplus::Rotate180FlipNone);
IStream* oStream = NULL;
CLSID tiffClsid;
GetEncoderClsid(L"image/tiff", &tiffClsid); // Function defined elsewhere
image.Save(oStream, &tiffClsid);
// And here's where I'm stumped.
(GetEncoderClsid)
So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string->Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route.
How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?
Got it
std::string RotateImage(const std::string &Base64EncodedImage)
{
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
std::string decodedImage = base64_decode(Base64EncodedImage);
DWORD imageSize = decodedImage.length();
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize);
LPVOID pImage = ::GlobalLock(hMem);
memcpy(pImage, decodedImage.c_str(), imageSize);
IStream* pStream = NULL;
::CreateStreamOnHGlobal(hMem, FALSE, &pStream);
Image image(pStream);
image.RotateFlip(Gdiplus::Rotate180FlipNone);
pStream->Release();
GlobalUnlock(hMem);
GlobalFree(hMem);
IStream* oStream = NULL;
CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)&oStream);
CLSID tiffClsid;
GetEncoderClsid(L"image/tiff", &tiffClsid);
image.Save(oStream, &tiffClsid);
ULARGE_INTEGER ulnSize;
LARGE_INTEGER lnOffset;
lnOffset.QuadPart = 0;
oStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize);
oStream->Seek(lnOffset, STREAM_SEEK_SET, NULL);
char *pBuff = new char[(unsigned int)ulnSize.QuadPart];
ULONG ulBytesRead;
oStream->Read(pBuff, (ULONG)ulnSize.QuadPart, &ulBytesRead);
std::string rotated_string = base64_encode((const unsigned char*)pBuff, ulnSize.QuadPart);
return rotated_string;
}
The trick, as inspired by what I got from this article, is knowing the method to finding out the size of the stream, and having it read it into a character array. Then I can feed that array to the base64_encode function and voilĂ .