Win32顯示jpg圖像

//第一步 加入stbi的兩個頭文件

#define STB_IMAGE_IMPLEMENTATION
#include "stbi/stb_image.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stbi/stb_image_write.h"
//第二步 讀取jpg圖片和繪製到hdc設備上

void show_jpg(HDC& hdc)
{
	//讀取圖像
	int width, height, channel;
	unsigned char* image_data = stbi_load("h:\\test.jpg", &width, &height, &channel, 3);
	unsigned char* image_buffer = new unsigned char[width * height *channel];

	//顏色通道數的翻轉和圖像像素的翻轉
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < width; j++)
		{
			image_buffer[((height - 1 - i) * width + j) *channel + 0] = image_data[(i* width + j) * channel + 2];
			image_buffer[((height - 1 - i) * width + j) *channel + 1] = image_data[(i* width + j) * channel + 1];
			image_buffer[((height - 1 - i) * width + j) *channel + 2] = image_data[(i* width + j) * channel + 0];
		}
	}

	//基本信息
	BITMAPINFOHEADER info{ 0 };
	info.biSize = sizeof(info);
	info.biPlanes = 1;
	info.biBitCount = channel * 8;
	info.biWidth = width;
	info.biHeight = height;
	info.biSizeImage = width * height * channel;

	//設置繪製模式位拉伸模式
	SetStretchBltMode(hdc, HALFTONE);

	//繪製
	StretchDIBits(hdc, 0, 0, width, height, 0, 0, width, height,
		image_buffer, (LPBITMAPINFO)&info, DIB_RGB_COLORS, SRCCOPY);

	//釋放內存
	delete[] image_data;
	delete[] image_buffer;
}
//第三步 更新圖像數據到窗口

    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
			show_jpg(hdc);
            EndPaint(hWnd, &ps);
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章