天天看點

怎樣顯示Jpg,bmp,Gif圖像檔案

LoadImage隻能加載bmp,ico,cur檔案,但是對于jpg,gif等檔案則無能為力,下面就是介紹用VC怎麼顯示jpg,gif,bmp檔案

1:LoadImage

HBITMAP hBitmap=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),"128.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_DEFAULTCOLOR|LR_DEFAULTSIZE);

2:GdiPlus

A. 在stdafx.h中或者cpp檔案的頭部引入下面兩條語句

     #include    <gdiplus.h>

     using namespace Gdiplus;

B. 在項目屬性-》連接配接器-》輸入-》附加依賴項中加入gdiplus.lib

C. 初始化gdiplus(一般在InitInstance或者OnInitDialog中加入)

   GdiplusStartupInput gdiplusStartupInput;

   ULONG_PTR           gdiplusToken;

   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

D.實作在一個Static(IDC_STATIC1)中顯示,在其它地方也可以隻要具有Window

  RECT rect;

  HDC hdc;

  PAINTSTRUCT ps;

 GetDlgItem(IDC_STATIC1)->GetClientRect(&rect);

 hdc = GetDlgItem(IDC_STATIC1)->GetWindowDC()->m_hDC;

 Graphics graphics(hdc); 

//由于Gdiplus::Image img()語句的參數必須是wchar_t *的形式,下面就是将檔案名strFileName從char *轉換為wchar_t *    

int wcsLen;

wchar_t* wszFileName;

 wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, strFileName, strlen(strFileName), NULL, 0);

 wszFileName = new wchar_t[wcsLen + 1];

 ::MultiByteToWideChar(CP_ACP, NULL, strFileName, strlen(strFileName), wszFileName, wcsLen);

 wszFileName[wcsLen] = '/0';

 Gdiplus::Image img(wszFileName);

 graphics.DrawImage(&img, 0, 0, rect.right - rect.left, rect.bottom - rect.top);

 ::ReleaseDC(GetDlgItem(IDC_STATIC1)->m_hWnd, hdc);

delete wszFileName;

繼續閱讀