Windows下从网络加载图片到内存中并立即显示到窗口上,不保存到磁盘:
#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
#pragma comment(lib, "ws2_32.lib")
#define BUF_LEN 10240
Bitmap *image;
void download(void)
{
WSADATA wsd;
WSAStartup(MAKEWORD(2, 2), &wsd);
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_addr.S_un.S_addr = inet_addr("192.168.0.4");
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
ZeroMemory(addr.sin_zero, sizeof(addr.sin_zero));
int i = connect(sock, (sockaddr *)&addr, sizeof(addr));
if (i == 0)
{
char *request = "GET /icons/ubuntu-logo.png HTTP/1.1\r\nHost: localhost\r\nAccept: image/png\r\nAccept-Language: en-US\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\n\r\n";
send(sock, request, strlen(request), NULL);
char *buffer = new char[BUF_LEN];
int size = recv(sock, buffer, BUF_LEN, NULL);
char *data;
for (data = buffer + 4; strncmp(data - 4, "\r\n\r\n", 4) != 0; data++);
int pngsize = size - (data - buffer);
HGLOBAL hMem = GlobalAlloc(GMEM_FIXED, pngsize);
char *pData = (char *)GlobalLock(hMem);
memcpy(pData, data, pngsize);
delete[] buffer;
GlobalUnlock(hMem);
IStream *stream;
CreateStreamOnHGlobal(hMem, TRUE, &stream);
image = Bitmap::FromStream(stream);
stream->Release();
}
closesocket(sock);
WSACleanup();
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
switch (uMsg)
{
case WM_CREATE:
download();
break;
case WM_DESTROY:
delete image;
PostQuitMessage(0);
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
{
Graphics graphics(hdc);
graphics.DrawImage(image, 10, 10);
}
EndPaint(hWnd, &ps);
break;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return FALSE;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
GdiplusStartupInput gdiplus;
ULONG_PTR gdiToken;
GdiplusStartup(&gdiToken, &gdiplus, NULL);
WNDCLASS wc;
wc.cbClsExtra = wc.cbWndExtra = 0;
wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = "ShowPNG";
wc.lpszMenuName = NULL;
wc.style = NULL;
RegisterClass(&wc);
HWND hWnd = CreateWindow(wc.lpszClassName, "Show PNG", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
GdiplusShutdown(gdiToken);
return 1;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiToken);
return msg.wParam;
}