IWICImagingFactory处理图像数据

最近使用Dirtect2D进行绘图操作,查阅了一些资料,也遇到了一些问题,其中部分问题网上也没有明确的正解(至少本人未找到),为止,本人记录一下,以供遇到同样问题的朋友们参考。

 

一,生成IWICImagingFactory

IWICImagingFactory* m_pIWICImagingFactory = NULL;
    		if (NULL == m_pIWICImagingFactory)
		{
			CoInitialize(NULL);
			CoCreateInstance(
				CLSID_WICImagingFactory,
				NULL,
				CLSCTX_INPROC_SERVER,
				IID_PPV_ARGS(&m_pIWICImagingFactory)
			);
		}

IWICImagingFactory这个是组件,所以需要调用CoInitialize(NULL);如果没有调用是生成不了IWICImagingFactory的

 

剩下的也就不多说了,直接调用测试函数(这个函数里面的buffer未释放)

GetID2D1BitmapFromImageData(
    ID2D1RenderTarget *pRenderTarget,
    IWICImagingFactory *pIWICFactory,
    void* pImageData,//RGB图像的buffer
    int imageW,//RGB图像的宽
    int ImageH,//RGB图像的高
    UINT destinationWidth,//目标图像的宽,因为这个函数进行了缩放操作,所以提供这个参数
    UINT destinationHeight,//目标图像的高,因为这个函数进行了缩放操作,所以提供这个参数
    ID2D1Bitmap **ppBitmap

 

HRESULT GetID2D1BitmapFromImageData(
	ID2D1RenderTarget *pRenderTarget,
	IWICImagingFactory *pIWICFactory,
	void* pImageData,
	int imageW,
	int ImageH,
	UINT destinationWidth,
	UINT destinationHeight,
	ID2D1Bitmap **ppBitmap
)
{
	HRESULT hr = S_OK;

	IWICBitmapDecoder *pDecoder = NULL;
	IWICBitmapFrameDecode *pSource = NULL;
	IWICStream *pStream = NULL;
	IWICFormatConverter *pConverter = NULL;
	IWICBitmapScaler *pScaler = NULL;
	static BYTE* buffer = NULL; //这里写静态的,只是为了测试,正式写的时候根据实际情况修改

	hr = pIWICFactory->CreateStream(&pStream);

	if (SUCCEEDED(hr))
	{
		if (!buffer)
		{
			BITMAPINFOHEADER bmiHdr; //定义信息头        
			bmiHdr.biSize = sizeof(BITMAPINFOHEADER);
			bmiHdr.biWidth = imageW;
			bmiHdr.biHeight = -ImageH;
			bmiHdr.biPlanes = 1;
			bmiHdr.biBitCount = 24;
			bmiHdr.biCompression = BI_RGB;
			bmiHdr.biSizeImage = imageW * ImageH * 3;
			bmiHdr.biXPelsPerMeter = 0;
			bmiHdr.biYPelsPerMeter = 0;
			bmiHdr.biClrUsed = 0;
			bmiHdr.biClrImportant = 0;

			BITMAPFILEHEADER fheader = { 0 };
			fheader.bfType = 'M' << 8 | 'B';
			fheader.bfSize = sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER) + bmiHdr.biSizeImage;
			fheader.bfOffBits = sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER);

			buffer = new BYTE[fheader.bfSize];
			memcpy(buffer, &fheader, sizeof(fheader));
			memcpy(buffer + sizeof(fheader), &bmiHdr, sizeof(bmiHdr));
		}
		
		memcpy(buffer + sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER), reinterpret_cast<BYTE*>(pImageData), imageW * ImageH * 3);
		/*
		//测试BITMAPINFO数据是否正确,如果正确则可以正确的保存out.bmp
		FILE* file;
		fopen_s(&file, "out.bmp", "wb");
		fwrite((const char*)(buffer), 1, fheader.bfSize, file);
		fclose(file);*/

		// Initialize the stream with the memory pointer and size.
		hr = pStream->InitializeFromMemory(
			reinterpret_cast<BYTE*>(buffer),
			imageW * ImageH * 3 + sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER)
		);

	}

	//网上很多说CreateDecoderFromStream创建失败(0x88982f50 未找到组件),实际是没有正确的生成pStream
	//参考https://stackoverflow.com/questions/9979848/iwicimagingfactorycreatedecoderfromstream-fails-error-message-message-is-no
	hr = pIWICFactory->CreateDecoderFromStream(
		pStream,
		NULL,
		WICDecodeMetadataCacheOnLoad,
		&pDecoder
	);
	

	/*
	//该方法用于测试CreateDecoderFromFilename, 如果使用该方法,可以注释上面Stream的部分
	if (!pDecoder)
	{
		hr = pIWICFactory->CreateDecoderFromFilename(
			_T("D:\\CheckImage3.bmp"),
			NULL,
			GENERIC_READ,
			WICDecodeMetadataCacheOnLoad,
			&pDecoder
		);
	}
	*/
	
	
	
	if (SUCCEEDED(hr))
	{

		// Create the initial frame.
		hr = pDecoder->GetFrame(0, &pSource);
	}



	if (SUCCEEDED(hr))
	{
		hr = pIWICFactory->CreateFormatConverter(&pConverter);
	}


	// If a new width or height was specified, create an
	// IWICBitmapScaler and use it to resize the image.
	if (destinationWidth != 0 || destinationHeight != 0)
	{
		if (SUCCEEDED(hr))
		{
			if (destinationWidth == 0)
			{
				UINT originalWidth, originalHeight;
				hr = pSource->GetSize(&originalWidth, &originalHeight);

				FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
				destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
			}
			else if (destinationHeight == 0)
			{
				UINT originalWidth, originalHeight;
				hr = pSource->GetSize(&originalWidth, &originalHeight);

				FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
				destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
			}

			hr = pIWICFactory->CreateBitmapScaler(&pScaler);
			
			if (SUCCEEDED(hr))
			{
				hr = pScaler->Initialize(
					pSource,
					destinationWidth,
					destinationHeight,
					WICBitmapInterpolationModeNearestNeighbor//WICBitmapInterpolationModeCubic
				);
			}
			if (SUCCEEDED(hr))
			{
				hr = pConverter->Initialize(
					pScaler,
					GUID_WICPixelFormat32bppPBGRA,
					WICBitmapDitherTypeNone,
					NULL,
					0.f,
					WICBitmapPaletteTypeMedianCut
				);
			}
			if (SUCCEEDED(hr))
			{
				//create a Direct2D bitmap from the WIC bitmap.
				hr = pRenderTarget->CreateBitmapFromWicBitmap(
					pConverter,
					NULL,
					ppBitmap
				);
				/*
				//从pConverter的内存中拷贝数据,效果同上面方法
				pConverter->GetSize(&destinationWidth, &destinationHeight);
				
				const UINT cbStride = destinationWidth * 4;
				const UINT cbImage = cbStride * destinationHeight;
				static BYTE * pvImageBits = new BYTE[cbImage];
				hr = pConverter->CopyPixels(NULL, cbStride, cbImage, pvImageBits);
				{
					(*ppBitmap)->CopyFromMemory(&D2D1::RectU(0, 0, destinationWidth, destinationHeight), pvImageBits, cbStride);
				}
				*/
			}
		}
	}

	
	SafeRelease(&pDecoder);

	SafeRelease(&pSource);

	SafeRelease(&pStream);

	SafeRelease(&pConverter);

	SafeRelease(&pScaler);
	return hr;
}

 

最后,DrawBitmap后,要记得释放掉生成的ppBitmap哦

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Direct2D 实现图像刚性弯曲的示例代码: ```cpp #include <Windows.h> #include <d2d1.h> #include <d2d1helper.h> #include <wincodec.h> #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "windowscodecs.lib") // 定义图像刚性变换的矩阵 D2D1_MATRIX_3X2_F g_transformMatrix = D2D1::Matrix3x2F(1, 0, 0, 0, 1, 0); // 定义 Direct2D 绘图对象 ID2D1Factory* g_pD2DFactory = nullptr; ID2D1HwndRenderTarget* g_pRenderTarget = nullptr; ID2D1Bitmap* g_pBitmap = nullptr; ID2D1BitmapBrush* g_pBitmapBrush = nullptr; // 定义窗口大小 const int g_width = 800; const int g_height = 600; // 加载位图文件 HRESULT LoadBitmapFromFile(ID2D1RenderTarget* pRenderTarget, IWICImagingFactory* pIWICFactory, LPCWSTR uri, UINT destinationWidth, UINT destinationHeight, ID2D1Bitmap** ppBitmap) { HRESULT hr = S_OK; // 创建 WIC 图像解码器 IWICBitmapDecoder* pDecoder = nullptr; hr = pIWICFactory->CreateDecoderFromFilename(uri, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &pDecoder); if (SUCCEEDED(hr)) { // 读取位图帧 IWICBitmapFrameDecode* pSource = nullptr; hr = pDecoder->GetFrame(0, &pSource); if (SUCCEEDED(hr)) { // 缩放位图 IWICBitmapScaler* pScaler = nullptr; hr = pIWICFactory->CreateBitmapScaler(&pScaler); if (SUCCEEDED(hr)) { UINT originalWidth = 0; UINT originalHeight = 0; hr = pSource->GetSize(&originalWidth, &originalHeight); if (SUCCEEDED(hr)) { FLOAT scaleX = static_cast<FLOAT>(destinationWidth) / originalWidth; FLOAT scaleY = static_cast<FLOAT>(destinationHeight) / originalHeight; WICPixelFormatGUID pixelFormat; hr = pSource->GetPixelFormat(&pixelFormat); if (SUCCEEDED(hr)) { if (scaleX != 1.0f || scaleY != 1.0f) { pScaler->Initialize(pSource, static_cast<UINT>(destinationWidth), static_cast<UINT>(destinationHeight), WICBitmapInterpolationModeCubic); pRenderTarget->CreateBitmapFromWicBitmap(pScaler, nullptr, ppBitmap); } else { pRenderTarget->CreateBitmapFromWicBitmap(pSource, nullptr, ppBitmap); } } } pScaler->Release(); } pSource->Release(); } pDecoder->Release(); } return hr; } // 初始化 Direct2D HRESULT InitializeDirect2D(HWND hWnd) { HRESULT hr = S_OK; // 创建 Direct2D 工厂 hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &g_pD2DFactory); if (SUCCEEDED(hr)) { // 获取窗口大小 RECT rc; GetClientRect(hWnd, &rc); D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top); // 创建 Direct2D 渲染目标 hr = g_pD2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size), &g_pRenderTarget); if (SUCCEEDED(hr)) { // 加载位图文件 IWICImagingFactory* pIWICFactory = nullptr; hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pIWICFactory)); if (SUCCEEDED(hr)) { hr = LoadBitmapFromFile(g_pRenderTarget, pIWICFactory, L"test.jpg", g_width, g_height, &g_pBitmap); if (SUCCEEDED(hr)) { // 创建位图画刷 hr = g_pRenderTarget->CreateBitmapBrush(g_pBitmap, &g_pBitmapBrush); if (SUCCEEDED(hr)) { // 设置画刷的平铺模式为重复 g_pBitmapBrush->SetExtendModeX(D2D1_EXTEND_MODE_WRAP); g_pBitmapBrush->SetExtendModeY(D2D1_EXTEND_MODE_WRAP); } } pIWICFactory->Release(); } } } return hr; } // 渲染场景 void RenderScene() { // 开始渲染 g_pRenderTarget->BeginDraw(); // 清空背景 g_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White)); // 应用刚性变换矩阵 g_pRenderTarget->SetTransform(g_transformMatrix); // 绘制位图 g_pRenderTarget->FillRectangle(D2D1::RectF(0, 0, g_width, g_height), g_pBitmapBrush); // 结束渲染 g_pRenderTarget->EndDraw(); } // 释放资源 void ReleaseResources() { SafeRelease(&g_pD2DFactory); SafeRelease(&g_pRenderTarget); SafeRelease(&g_pBitmap); SafeRelease(&g_pBitmapBrush); } // 处理窗口消息 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: // 初始化 Direct2D if (FAILED(InitializeDirect2D(hWnd))) { MessageBox(hWnd, L"初始化 Direct2D 失败", L"错误", MB_OK | MB_ICONERROR); return -1; } break; case WM_PAINT: // 渲染场景 RenderScene(); ValidateRect(hWnd, NULL); break; case WM_SIZE: // 重新创建渲染目标 ReleaseResources(); if (FAILED(InitializeDirect2D(hWnd))) { MessageBox(hWnd, L"初始化 Direct2D 失败", L"错误", MB_OK | MB_ICONERROR); return -1; } break; case WM_DESTROY: // 释放资源 ReleaseResources(); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // WinMain 函数 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 注册窗口类 WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = L"Direct2DApp"; RegisterClassEx(&wcex); // 创建窗口 HWND hWnd = CreateWindow(L"Direct2DApp", L"Direct2D App", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, g_width, g_height, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } // 显示窗口 ShowWindow(hWnd, nCmdShow); // 消息循环 MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } ``` 在上面的示例代码中,`g_transformMatrix` 变量表示图像的刚性变换矩阵,可以使用 `D2D1::Matrix3x2F` 函数来创建。在 `RenderScene` 函数中,可以使用 `g_pRenderTarget->SetTransform` 函数来应用刚性变换矩阵。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值