Thursday, March 29, 2007

Load JPEG,GIF files in VC++ :

Once again it is only for VC++ guys... To load JPEG in VC++ is a headache problem...

Now we can use this function to load JPEG,GIF and all picture file formats...
Header files to be included :
#include <olectl.h>
#include <ole2.h>
All u need is to pass the device context and the filename to it....
This is the function to load the JPEG images
// Function LoadAnImage: accepts a file name
void LoadAnImage(HDC hdc,char* FileName)
{
// Use IPicture stuff to use JPG / GIF files
IPicture* p;
IStream* s;
IPersistStream* ps;
HGLOBAL hG;
void* pp;
FILE* fp;


// Read file in memory
fp = fopen(FileName,"rb");
if (!fp)
return;

fseek(fp,0,SEEK_END);
int fs = ftell(fp);
fseek(fp,0,SEEK_SET);
hG = GlobalAlloc(GPTR,fs);


if (!hG)
{
fclose(fp);
return;
}


pp = (void*)hG;
fread(pp,1,fs,fp);
fclose(fp);

// Create an IStream so IPicture can
// CreateStreamOnHGlobal(hG,false,&s);
CreateStreamOnHGlobal(hG,false,&s);
if (!s)
{
GlobalFree(hG);
return;
}

OleLoadPicture(s,0,false,IID_IPicture,(void**)&p);

if (!p)
{
s->Release();
GlobalFree(hG);
return;
}

s->Release();
GlobalFree(hG);


long hmHeight;
long hmWidth;

HBITMAP hB = 0;


p->get_Handle((unsigned int*)&hB);
p->get_Height(&hmHeight);
p->get_Width(&hmWidth);


p->Render(hdc,0,0,300,300,0,hmHeight,hmWidth,-hmHeight,NULL);
p->Release();

}
How can we use it ?....
From windows SDK ...
HDC hdc = GetDC(hwnd);
LoadAnImage(hdc,"D:\Test.jpg");
ReleaseDC(hdc );
if u are using MFC ,
CClientDC dc(this );
LoadAnImage(dc->m_hDC,"D:test.jpg");
we may pass the control's (command buttons...) device context, which in turn draws the picture over the control.....

No comments: