Tuesday, April 8, 2008

Displaying an Image in Windows - 2

In the last post, for purposes of illustration, all the code was written in the DisplayImage() function. However that need not be so. For instance, the opening of the file, and reading of the image bits into the rawimg variable can be done in other functions within the dialog class. We can even push the lines where the rawimg bytes are transferred into ImageDisp32Bit into a different function (we must take care of proper freeing of variables, however). However, it is preferable to retain the lines where the bitmap bm1 is created, and then displayed in the function DisplayImage() itself.

In the last post, we saw StretchBlt(), where the image was stretched or shrunk to the required dimensions. There is another function called BitBlt() of the same class CDC which draws an image at the same size as the original. Using BitBlt(), you can display the image to the zoom ratio 1:1 only. From what I know, BitBlt() does not fail for large images, and is the fastest way to display an image.

The prototype of the BitBlt() function is:
BOOL CDC::BitBlt(int x, int y, int nWidth, int nHeight, CDC * pSrcDC, int xSrc, int ySrc, DWORD dwRop).

A code extract illustrating the use of BitBlt() is given below:

void CDisplayImageDlg::DisplayImage()
{
char *ImageDisp32Bit = NULL;
ImageDisp32Bit = (char *)malloc(imageWidth * imageHeight * 4);
char *rawimg = NULL;
rawimg = (char *)malloc(imageWidth * imageHeight);
FILE *fl=fopen(fileName, "rb");
fread(rawimg, imageWidth * imageHeight, 1, fl);
fclose(fl);
int i = 0;
for(int m = 0; m <>
{
*(ImageDisp32Bit + i) = *(rawimg + m); i++;
*(ImageDisp32Bit + i) = *(rawimg + m); i++;
*(ImageDisp32Bit + i) = *(rawimg + m); i++;
*(ImageDisp32Bit + i) = *(rawimg + m); i++;
}
CBitmap bm1;
bm1.CreateBitmap(imageWidth,imageHeight, 1, 32, ImageDisp32Bit);
free(ImageDisp32Bit);
free(rawimg);
CDC *dcptr=this->GetDC();
CDC bitmapdc1;
bitmapdc1.CreateCompatibleDC(this->GetDC());
bitmapdc1.SelectObject(&bm1);
dcptr->SetStretchBltMode(HALFTONE);
dcptr->SetBkMode(TRANSPARENT);
dcptr->BitBlt(10, 10, 850, 560, &bitmapdc1, 0, 0, SRCCOPY);
dcptr->SetTextColor(RGB(240,50,50));
dcptr->TextOut(10,10,fileName);
dcptr->ReleaseOutputDC();
}




With this post, we have seen two ways to display an image - one using StretchBlt() and another using BitBlt(), both being functions of the class CDC.




No comments: