HRESULT DemoApp::CreateProgressiveCtrlFromFile(HWND hWnd)
{
    HRESULT hr = S_OK;

    WCHAR szFileName[MAX_PATH];

    // Create the open dialog box and locate the image file
    if (LocateImageFile(hWnd, szFileName, ARRAYSIZE(szFileName)))
    {
        // Create a decoder
        IWICBitmapDecoder *pDecoder = NULL;

        hr = m_pIWICFactory->CreateDecoderFromFilename(
            szFileName,                      // Image to be decoded
            NULL,                            // Do not prefer a particular vendor
            GENERIC_READ,                    // Desired read access to the file
            WICDecodeMetadataCacheOnDemand,  // Cache metadata when needed
            &pDecoder                        // Pointer to the decoder
            );

        // Retrieve the first frame of the image from the decoder
        if (SUCCEEDED(hr))
        {
            // Need to release the previously source bitmap.
            // For each new image file, we need to create a new source bitmap
            SafeRelease(m_pSourceFrame);
            hr = pDecoder->GetFrame(0, &m_pSourceFrame);
        }

        IWICProgressiveLevelControl *pProgressive = NULL;

        if (SUCCEEDED(hr))
        {
            // Query for Progressive Level Control Interface
            hr = m_pSourceFrame->QueryInterface(IID_PPV_ARGS(&pProgressive));

            // Update progressive level count and reset the current level
            if (SUCCEEDED(hr))
            {
                m_uCurrentLevel = 0;
                hr = pProgressive->GetLevelCount(&m_uLevelCount);
            }
            else
            {
                MessageBox(hWnd, L"Image has no progressive encoding, select another one.", L"Application Error", 
                    MB_ICONEXCLAMATION | MB_OK);
            }
        }
        else
        {
            MessageBox(hWnd, L"Failed to load image, select another one.", L"Application Error", 
                MB_ICONEXCLAMATION | MB_OK);
        }

        SafeRelease(pDecoder);
        SafeRelease(pProgressive);
    }

    return hr;
}
Example #2
0
Image::Buffer * WIC::Api::CreateImage(char * buffer, unsigned bufferLength)
{
	if(!factory) return 0;

	// Create input stream for memory
	IWICStream * stream = 0;
	factory->CreateStream(&stream);
	if(!stream) return 0;

	stream->InitializeFromMemory((unsigned char*)(buffer), static_cast<DWORD>(bufferLength));

	IWICBitmapDecoder * decoder = 0;
	factory->CreateDecoderFromStream(stream, 0, WICDecodeMetadataCacheOnDemand, &decoder);
	if(!decoder) return 0;

	IWICBitmapFrameDecode * bitmapSource = 0;
	decoder->GetFrame(0, &bitmapSource);
	if(!bitmapSource)
	{
		decoder->Release();
		return 0;
	}

	IWICBitmapSource * convertedSource = 0;
	WICConvertBitmapSource(GUID_WICPixelFormat32bppRGBA, bitmapSource, &convertedSource);
	bitmapSource->Release();
	if(!convertedSource)
	{
		decoder->Release();
		return 0;
	}

	// Create the bitmap from the image frame.
	IWICBitmap * bitmap = 0;
	factory->CreateBitmapFromSource(
		convertedSource,         // Create a bitmap from the image frame
		WICBitmapCacheOnDemand,  // Cache metadata when needed
		&bitmap);                // Pointer to the bitmap

	convertedSource->Release();
	decoder->Release();

	if(!bitmap) return 0;

	unsigned width = 0, height = 0;
	bitmap->GetSize(&width, &height);
	WICRect lockRect = { 0, 0, width, height };

	IWICBitmapLock * lock = 0;
	bitmap->Lock(&lockRect, WICBitmapLockWrite, &lock);
	if(!lock)
	{
		bitmap->Release();
		return 0;
	}

	return new WIC::Buffer(bitmap, lock, width, height);
}
SpriteSheet::SpriteSheet(wchar_t* filename, Graphics* gfx)
{
	this->gfx = gfx;
	bmp = NULL;
	HRESULT hr;

	//create a wic factory 
	IWICImagingFactory *wicFactory = NULL;
	hr = CoCreateInstance(
		CLSID_WICImagingFactory,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IWICImagingFactory,
		(LPVOID*)&wicFactory);

	//create a decoder
	IWICBitmapDecoder *wicDecoder = NULL;
	hr = wicFactory->CreateDecoderFromFilename(
		filename,       // THE FILE NAME
		NULL,           // the preferred vendor
		GENERIC_READ,   // we're reading the file, not writing
		WICDecodeMetadataCacheOnLoad,
		&wicDecoder);

	// read a frame from the image
	IWICBitmapFrameDecode* wicFrame = NULL;
	hr = wicDecoder->GetFrame(0, &wicFrame);

	// create a converter
	IWICFormatConverter *wicConverter = NULL;
	hr = wicFactory->CreateFormatConverter(&wicConverter);

	// setup the converter
	hr = wicConverter->Initialize(
		wicFrame,                      // frame
		GUID_WICPixelFormat32bppPBGRA, // pixel format
		WICBitmapDitherTypeNone,       // irrelevant
		NULL,             // no palette needed, irrlevant
		0.0,              // alpha transparency % irrelevant
		WICBitmapPaletteTypeCustom     // irrelevant
		);

	// use the converter to create an D2D1Bitmap
	/// ID2D1Bitmap* bmp;      // this will be a member variable
	hr = gfx->GetRenderTarget()->CreateBitmapFromWicBitmap(
		wicConverter,      // converter
		NULL,              // D2D1_BITMAP_PROPERIES
		&bmp               // destiatnion D2D1 bitmap
		);

	if (wicFactory) wicFactory->Release();
	if (wicDecoder) wicDecoder->Release();
	if (wicConverter) wicConverter->Release();
	if (wicFrame) wicFrame->Release();

}
HBITMAP ImageDecoder::loadImage(unsigned char *bytes, int size)
{
	IWICStream *stream = createStreamFromBytes(bytes, size);
	IWICBitmapDecoder *decoder = createDecoderFromStream(stream);

	HBITMAP bitmap = loadImage(decoder);

	decoder->Release();
	stream->Release();

	return bitmap;
}
Example #5
0
HRESULT d2d::LoadBitmap (
	const wchar_t* filename,
	IWICImagingFactory* wic,
	ID2D1RenderTarget* rt,
	ID2D1Bitmap **bitmap )
{
	HRESULT hr = S_OK;
	IWICBitmapFrameDecode *frame = nullptr;
	IWICBitmapDecoder *decoder = nullptr;
	IWICFormatConverter *conv = nullptr;
 
	// 디코더 생성
	hr = wic->CreateDecoderFromFilename (
			filename,
			0,
			GENERIC_READ,
			WICDecodeMetadataCacheOnDemand,
			&decoder );
 
	// 프레임 얻기
	if(SUCCEEDED(hr))
		hr = decoder->GetFrame (0, &frame);
 
	// 변환기 생성
	if(SUCCEEDED(hr))
		hr = wic->CreateFormatConverter(&conv);
	
	// 변환기 초기화
	if(SUCCEEDED(hr))
		hr = conv->Initialize (
				frame,
				GUID_WICPixelFormat32bppPBGRA,
				WICBitmapDitherTypeNone,
				0,
				1.0f,
				WICBitmapPaletteTypeCustom );
 
	// 비트맵 생성
	if(SUCCEEDED(hr))
		hr = rt->CreateBitmapFromWicBitmap (
				conv,
				bitmap );
	
	// 해제
	d2d::SafeRelease(frame);
	d2d::SafeRelease(decoder);
	d2d::SafeRelease(conv);
 
	// 결과 반환
	return hr;
}
Example #6
0
//从一个文件加载图片
ID2D1Bitmap* d2d::CreateBitmapFromFile(wstring strFileName)
{
    IWICBitmapDecoder *pDecoder = nullptr;
    HRESULT hr = m_pWICFactory->CreateDecoderFromFilename(strFileName.c_str(), NULL, GENERIC_READ,
                                                          WICDecodeMetadataCacheOnLoad, //enum WICDecodeOptions
                                                          &pDecoder);

    if (FAILED(hr))
    {
        return nullptr;
    }

     // Create the initial frame.
    IWICBitmapFrameDecode *pSource = nullptr;
    hr = pDecoder->GetFrame(0, &pSource);
    if (FAILED(hr))
    {
        return nullptr;
    }

    //转换器
    IWICFormatConverter *pConverter = nullptr;
    hr = m_pWICFactory->CreateFormatConverter(&pConverter);
    if (FAILED(hr))
    {
        return nullptr;
    }

    hr = pConverter->Initialize(pSource, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone,
                                NULL, 0.f, WICBitmapPaletteTypeMedianCut);
 
    if (FAILED(hr))
    {
        return nullptr;
    }
    
    // Create a Direct2D bitmap from the WIC bitmap.
    ID2D1Bitmap* picBitmap = nullptr;
    hr = m_pRenderTarget->CreateBitmapFromWicBitmap(pConverter, NULL, &picBitmap);
    if (FAILED(hr))
    {
        return nullptr;
    }

    SafeRelease(pDecoder);
    SafeRelease(pSource);
    SafeRelease(pConverter);

    return picBitmap;
}
Example #7
0
HBITMAP LoadLocalPNG( const std::string& sPath, const RASize& sz )
{
	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );

	ASSERT( _FileExists( sPath ) );
	if( !_FileExists( sPath ) )
	{
		RA_LOG( "File could not be found: %s\n", sPath.c_str() );
		return nullptr;
	}

	HBITMAP hRetVal = nullptr;
	// Step 2: Decode the source image to IWICBitmapSource
	IWICBitmapDecoder* pDecoder = nullptr;
	HRESULT hr = g_UserImageFactoryInst.m_pIWICFactory->CreateDecoderFromFilename( Widen( sPath ).c_str(),			// Image to be decoded
																				   nullptr,							// Do not prefer a particular vendor
																				   GENERIC_READ,					// Desired read access to the file
																				   WICDecodeMetadataCacheOnDemand,	// Cache metadata when needed
																				   &pDecoder );						// Pointer to the decoder
	
	// Retrieve the first frame of the image from the decoder
	IWICBitmapFrameDecode* pFrame = nullptr;
	if( SUCCEEDED( hr ) )
		hr = pDecoder->GetFrame( 0, &pFrame );

	// Retrieve IWICBitmapSource from the frame
	if( SUCCEEDED( hr ) )
	{
		SAFE_RELEASE( g_UserImageFactoryInst.m_pOriginalBitmapSource );	//##SD ???
		pFrame->QueryInterface( IID_IWICBitmapSource, reinterpret_cast<void**>( &g_UserImageFactoryInst.m_pOriginalBitmapSource ) );
	}

	// Step 3: Scale the original IWICBitmapSource to the client rect size
	// and convert the pixel format
	IWICBitmapSource* pToRenderBitmapSource = nullptr;
	if( SUCCEEDED( hr ) )
		hr = ConvertBitmapSource( { 0, 0, sz.Width(), sz.Height() }, pToRenderBitmapSource );

	// Step 4: Create a DIB from the converted IWICBitmapSource
	if( SUCCEEDED( hr ) )
		hr = UserImageFactory_CreateDIBSectionFromBitmapSource( pToRenderBitmapSource, hRetVal );

	SAFE_RELEASE( pToRenderBitmapSource );
	SAFE_RELEASE( pDecoder );
	SAFE_RELEASE( pFrame );
	SAFE_RELEASE( g_UserImageFactoryInst.m_pOriginalBitmapSource );
	
	return hRetVal;
}
Example #8
0
// Loads a PNG image from the specified stream (using Windows Imaging Component).
IWICBitmapSource * LoadBitmapFromStream(IStream * ipImageStream)
{
	// initialize return value
	IWICBitmapSource * ipBitmap = NULL;

	// load WIC's PNG decoder
	IWICBitmapDecoder * ipDecoder = NULL;
	IID i = IID_IWICBitmapDecoder;

	if (FAILED(CoCreateInstance(CLSID_WICPngDecoder, NULL, CLSCTX_INPROC_SERVER,
		i,//__uuidof(ipDecoder)

		(void **)&ipDecoder)))
		goto Return;


	// load the PNG
	if (FAILED(ipDecoder->Initialize(ipImageStream, WICDecodeMetadataCacheOnLoad)))
		goto ReleaseDecoder;

	// check for the presence of the first frame in the bitmap
	UINT nFrameCount = 0;

	if (FAILED(ipDecoder->GetFrameCount(&nFrameCount)) || nFrameCount != 1)
		goto ReleaseDecoder;

	// load the first frame (i.e., the image)
	IWICBitmapFrameDecode * ipFrame = NULL;

	if (FAILED(ipDecoder->GetFrame(0, &ipFrame)))
		goto ReleaseDecoder;


	// convert the image to 32bpp BGRA format with pre-multiplied alpha
	//   (it may not be stored in that format natively in the PNG resource,
	//   but we need this format to create the DIB to use on-screen)
	WICConvertBitmapSource(GUID_WICPixelFormat32bppPBGRA, ipFrame, &ipBitmap);
	ipFrame->Release();

ReleaseDecoder:
	ipDecoder->Release();

Return:
	return ipBitmap;

}
Example #9
0
/// <summary>
/// Tries to get the cover from the specified folder.
/// </summary>
/// <param name="filePath">Path to the file to get the cover from.</param>
bool CoverArt::SetCoverFromFolder(LPCWSTR filePath)
{
    WCHAR folderPath[MAX_PATH] = {0};
    IWICImagingFactory *factory = nullptr;
    IWICBitmapDecoder *decoder = nullptr;
    IWICBitmapFrameDecode *source = nullptr;
    HRESULT hr = E_FAIL;

    StringCchCopyW(folderPath, _countof(folderPath), filePath);
    PathRemoveFileSpecW(folderPath);

    // Check each covername
    WCHAR artPath[MAX_PATH];
    for (auto &canidate : mFolderCanidates)
    {
        StringCchPrintfW(artPath, _countof(artPath), L"%s\\%s", folderPath, canidate.c_str());
        for (auto &file : FileIterator(artPath))
        {
            StringCchPrintfW(artPath, _countof(artPath), L"%s\\%s", folderPath, file.cFileName);

            hr = Factories::GetWICFactory(reinterpret_cast<LPVOID*>(&factory));
            if (SUCCEEDED(hr))
            {
                hr = factory->CreateDecoderFromFilename(artPath, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder);
            }
            if (SUCCEEDED(hr))
            {
                hr = decoder->GetFrame(0, &source);
            }
            if (SUCCEEDED(hr))
            {
                SendMessage(gLSModule.GetMessageWindow(), WM_COVERARTUPDATE, (WPARAM)this, (LPARAM)source);
            }

            SAFERELEASE(decoder);

            if (SUCCEEDED(hr))
            {
                return true;
            }
        }
    }
    
    return false;
}
Example #10
0
// =========================================================
// Load the specified bitmap from file into D2D bitmap
// =========================================================
BOOL Loader::LoadBitmapFromFile(LPCWSTR filename, const Graphics* graphicsWrapper, ID2D1Bitmap** ppBitmap)
{
	if (!isInitialized)
		return FALSE;

	HRESULT hr;

	IWICBitmapDecoder *pDecoder = NULL;
	IWICBitmapFrameDecode *pSource = NULL;
	IWICFormatConverter *pConverter = NULL;

	hr = pFactory->CreateDecoderFromFilename(filename, NULL, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &pDecoder);
	CHECK(failedDecoder);

	hr = pDecoder->GetFrame(0, &pSource);
	CHECK(failedGetFrame);

	hr = pFactory->CreateFormatConverter(&pConverter);
	CHECK(failedConverter);

	hr = pConverter->Initialize(pSource, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeMedianCut);
	CHECK(failedConversion);

	hr = graphicsWrapper->pRenderTarget->CreateBitmapFromWicBitmap(pSource, ppBitmap);
	CHECK(failedBitmap);

	return TRUE;

failedBitmap:
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create bitmap.\n");
failedConversion:
	pConverter->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to initialise format converter.\n");
failedConverter:
	pSource->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create format converter.\n");
failedGetFrame:
	pDecoder->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to get frame 0 from source bitmap.\n");
failedDecoder:
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create bitmap decoder.\n");
	return FALSE;
}
HBITMAP ImageDecoder::loadImage(const std::string &filename)
{
	WCHAR *wcharFilename = buildWcharString(filename);
	IWICBitmapDecoder *decoder = NULL;
	HRESULT result = factory->CreateDecoderFromFilename(wcharFilename, NULL, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder);

	delete[] wcharFilename;

	if (FAILED(result))
	{
		throw Exception("could not create decoder");
	}

	HBITMAP bitmap = loadImage(decoder);

	decoder->Release();

	return bitmap;
}
Example #12
0
HRESULT CAshaD2D::CreateD2DBitmapFromFile(HWND hWnd)
{
	HRESULT hr = S_OK;

	WCHAR szFileName[MAX_PATH];

	// Step 1: Create the open dialog box and locate the image file
	if (OpenFile(hWnd, szFileName, ARRAYSIZE(szFileName)))
	{
		// Step 2: Decode the source image

		// Create a decoder
		IWICBitmapDecoder *pDecoder = NULL;

		hr = m_pWICImgFactory->CreateDecoderFromFilename(
			szFileName,                      // Image to be decoded
			NULL,                            // Do not prefer a particular vendor
			GENERIC_READ,                    // Desired read access to the file
			WICDecodeMetadataCacheOnDemand,  // Cache metadata when needed
			&pDecoder                        // Pointer to the decoder
			);

		// Retrieve the first frame of the image from the decoder
		//IWICBitmapFrameDecode *pFrame = NULL;

		if (SUCCEEDED(hr))
		{
			SafeRelease(&m_pFrame);
			hr = pDecoder->GetFrame(0, &m_pFrame);
		}

		


		//SafeRelease(&pfmatCoverter);
		SafeRelease(&pDecoder);
		//SafeRelease(&pFrame);
	}

	return hr;
}
Example #13
0
// ----------------------------------------------------------------
//	LoadResource
// ----------------------------------------------------------------
bool CD2DBitmap::LoadResource( ResourceId id )
{
	ID2D1HwndRenderTarget * renderTarget = CD2DRenderer::GetInstance().GetHwndRenderTarget();
	IWICImagingFactory * imagingFactory = CD2DRenderer::GetInstance().GetImagingFactory();

	IWICBitmapDecoder * bitmapDecoder = nullptr;
	IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;

	imagingFactory->CreateDecoderFromFilename( id.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &bitmapDecoder );
	bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );

	imagingFactory->CreateFormatConverter( &m_FmtConverter );
	m_FmtConverter->Initialize( bitmapFrameDecode, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.0f, WICBitmapPaletteTypeCustom );

	renderTarget->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );

	SafeRelease( bitmapDecoder );
	SafeRelease( bitmapFrameDecode );

	return true;
}
Example #14
0
void GL::Image::load(const unsigned char *buf, size_t bufSize)
{
    if (CoInitializeEx(NULL, COINIT_MULTITHREADED) != S_OK) {
        // bad!
        return;
    }
    IStream *stream = SHCreateMemStream((const BYTE*)buf, (UINT)bufSize);
    if (stream != NULL) {
        IWICImagingFactory *pFactory;
        if (CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory) == S_OK) {
            IWICBitmapDecoder *pDecoder;
            if (pFactory->CreateDecoderFromStream(stream, &CLSID_WICPngDecoder, WICDecodeMetadataCacheOnDemand, &pDecoder) == S_OK) {
                IWICBitmapFrameDecode *frame;
                if (pDecoder->GetFrame(0, &frame) == S_OK) {
                    UINT w, h;
                    if (frame->GetSize(&w, &h) == S_OK) {
                        width_ = w;
                        height_ = h;
                    }
                    IWICFormatConverter *formatConverter;
                    if (pFactory->CreateFormatConverter(&formatConverter) == S_OK) {
                        if (formatConverter->Initialize(frame, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.0, WICBitmapPaletteTypeCustom) == S_OK) {
                            unsigned char *pixels = new unsigned char[w * h * 4];
                            if (formatConverter->CopyPixels(0, w * 4, w * h * 4, pixels) == S_OK) {
                                loadTextureData_(pixels);
                            }
                            delete[] pixels;
                        }
                        formatConverter->Release();
                    }
                }
                pDecoder->Release();
            }
            pFactory->Release();
        }
        stream->Release();
    }
    CoUninitialize();
}
void ImageDecoder::loadGifFromResource(const WCHAR *name, const WCHAR *type, std::vector<AnimatedGifFrame *> &frames)
{
	unsigned char *bytes = NULL;
	DWORD size = 0;
	loadResource(name, type, bytes, size);

	IWICStream *stream = createStreamFromBytes(bytes, size);
	IWICBitmapDecoder *decoder = createDecoderFromStream(stream);

	unsigned int frameCount = 0;
	if (FAILED(decoder->GetFrameCount(&frameCount)))
	{
		throw Exception("could not get gif frame count");
	}

	if (frameCount <= 1)
	{
		throw Exception("not a gif animation");
	}

	for (unsigned int frameIndex = 0; frameIndex < frameCount; frameIndex++)
	{
		IWICBitmapFrameDecode *bitmapFrame = NULL;
		if (FAILED(decoder->GetFrame(frameIndex, &bitmapFrame)))
		{
			throw Exception("could not get frame");
		}

		HBITMAP bitmap = convertFrameToBitmap(bitmapFrame);
		bitmapFrame->Release();

		AnimatedGifFrame *frame = new AnimatedGifFrame(bitmap);
		frames.push_back(frame);

	}

	decoder->Release();
	stream->Release();
}
Example #16
0
NND2DTexture::NND2DTexture( std::wstring path )
{
	if ( g_pWICFactory == nullptr)
	{
		HRESULT ret = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
		if( ret == REGDB_E_CLASSNOTREG ) 
		{
			 CoCreateInstance( CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pWICFactory) );
		}
	}

	m_Path = path;

	IWICBitmapDecoder* bitmapDecoder = nullptr;
	g_pWICFactory->CreateDecoderFromFilename( path.c_str(), nullptr, GENERIC_READ, 
		WICDecodeMetadataCacheOnDemand, &bitmapDecoder );

	IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
	bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );

	g_pWICFactory->CreateFormatConverter( &m_FmtConverter );

	m_FmtConverter->Initialize( bitmapFrameDecode,
		GUID_WICPixelFormat32bppPBGRA,
		WICBitmapDitherTypeNone,
		nullptr,
		0.0f,
		WICBitmapPaletteTypeCustom );

	NND2DRenderer* pD2DRenderer = static_cast<NND2DRenderer*>(NNApplication::GetInstance()->GetRenderer());

	pD2DRenderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap( m_FmtConverter, nullptr, &m_D2DBitmap );

	SafeRelease( bitmapDecoder );
	SafeRelease( bitmapFrameDecode );
}
// Create a Direct2D bitmap from the specified file name
HRESULT DemoApp::LoadBitmapFromFile(
	ID2D1RenderTarget *pRenderTarget,
	IWICImagingFactory *pIWICFactory,
	PCWSTR uri,
	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;

	hr = pIWICFactory->CreateDecoderFromFilename(
		uri, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &pDecoder);
	if (SUCCEEDED(hr))
	{
		// Create the initial frame
		hr = pDecoder->GetFrame(0, &pSource);
	}

	if (SUCCEEDED(hr))
	{
		// Convert the image format to 32bppPBGRA
		// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
		hr = pIWICFactory->CreateFormatConverter(&pConverter);
	}
	if (SUCCEEDED(hr))
	{
		// If a new width or height was specified, create an
		// IWICBitmapScaler and use it to resize the image.
		if (destinationWidth != 0 || destinationHeight != 0)
		{
			UINT originalWidth, originalHeight;
			hr = pSource->GetSize(&originalWidth, &originalHeight);
			if (SUCCEEDED(hr))
			{
				if (destinationWidth == 0)
				{
					FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
					destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
				}
				else if (destinationHeight == 0)
				{
					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,
						WICBitmapInterpolationModeCubic);
				}
				if (SUCCEEDED(hr))
				{
					hr = pConverter->Initialize(
						pScaler,
						GUID_WICPixelFormat32bppPBGRA,
						WICBitmapDitherTypeNone,
						NULL,
						0.f,
						WICBitmapPaletteTypeMedianCut);
				}
			}
		}
		else // Don't scale the image.
		{
			hr = pConverter->Initialize(
				pSource,
				GUID_WICPixelFormat32bppPBGRA,
				WICBitmapDitherTypeNone,
				NULL,
				0.f,
				WICBitmapPaletteTypeMedianCut);
		}
	}
	if (SUCCEEDED(hr))
	{
		// Create a Direct2D bitmap from the WIC bitmap.
		hr = pRenderTarget->CreateBitmapFromWicBitmap(
			pConverter,
			NULL,
			ppBitmap);
	}

	SafeRelease(&pDecoder);
	SafeRelease(&pSource);
	SafeRelease(&pStream);
	SafeRelease(&pConverter);
	SafeRelease(&pScaler);

	return hr;
}
Example #18
0
Bitmap::Bitmap( std::wstring bitmapPath )
{
	HRESULT hr;
	if( m_WICFactory == nullptr )
	{
		hr = CoCreateInstance( CLSID_WICImagingFactory ,
							   NULL , CLSCTX_INPROC_SERVER ,
							   IID_PPV_ARGS( &m_WICFactory ) );
		if( hr == REGDB_E_CLASSNOTREG )
		{
			CoCreateInstance( CLSID_WICImagingFactory1 ,
							  NULL , CLSCTX_INPROC_SERVER ,
							  IID_PPV_ARGS( &m_WICFactory ) );
		}
	}

	m_Path = bitmapPath;
	IWICBitmapDecoder* bitmapDecoder = nullptr;
	hr = m_WICFactory->CreateDecoderFromFilename(
		bitmapPath.c_str() , nullptr , GENERIC_READ ,
		WICDecodeMetadataCacheOnDemand , &bitmapDecoder
		);

	IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
	if( SUCCEEDED( hr ) )
	{
		bitmapDecoder->GetFrame( 0 , &bitmapFrameDecode );
	}

	if( SUCCEEDED( hr ) )
	{
		hr = m_WICFactory->CreateFormatConverter( &m_FmtConverter );
	}

	if( SUCCEEDED( hr ) )
	{
		hr = m_FmtConverter->Initialize(
			bitmapFrameDecode , GUID_WICPixelFormat32bppPBGRA ,
			WICBitmapDitherTypeNone , NULL ,
			0.f , WICBitmapPaletteTypeCustom
			);
	}

	D2DRenderer* renderer = BattleShipApp::GetInstance()->GetD2DRenderer();

	if( m_FmtConverter != nullptr )
	{
		renderer->GetHwndRenderTarget()->CreateBitmapFromWicBitmap(
			m_FmtConverter , nullptr , &m_D2DBitmap );
	}

	if( bitmapDecoder != nullptr )
	{
		bitmapDecoder->Release();
	}
	if( bitmapFrameDecode != nullptr )
	{
		bitmapFrameDecode->Release();
	}

}
Example #19
0
//  解码照片的基础位图文件的.
HRESULT VideoEncoder::DecodeFrame(Photo* pPhoto, BYTE** ppOutputBitmap, int* pBitmapSize)
{
	HRESULT hr = S_OK;

	IWICBitmapDecoder *pDecoder  = nullptr;
	IWICBitmapFrameDecode *pFrame  = nullptr;
	IWICBitmap* pSourceBitmap = nullptr;
	IWICBitmapLock* pLock = nullptr;
	BYTE* pSourceBuffer = nullptr;
	BYTE* pDestinationBuffer = nullptr;
	UINT pixelWidth;
	UINT pixelHeight;
	WICRect lockRect;

	*ppOutputBitmap = nullptr;
		hr = m_pIWICFactory->CreateDecoderFromFilename(
		pPhoto->GetFile().c_str(),
		nullptr,
		GENERIC_READ,
		WICDecodeMetadataCacheOnDemand,
		&pDecoder
		);
	CheckHR(hr);
	this->m_logFileStream << "WIC解码器创建成功." << endl;
	GUID containerFormat;
	CheckHR(pDecoder->GetContainerFormat(&containerFormat));

	// 我们仅支持jpg 文件.
	if (containerFormat != GUID_ContainerFormatJpeg)
	{
		this->m_logFileStream << "仅支持jpeg文件." << endl;
		return E_NOTSUPPORTEDFORMAT;
	}

	// 我们仅支持jpg 文件. 因此只有一桢.
	CheckHR(pDecoder->GetFrame(0, &pFrame));

	// TODO: 目前我们需要所有照片有相同的大小.
	// 如果需求在将来发生变化,修改代码.
	pFrame->GetSize(&pixelWidth, &pixelHeight);
	if (pixelWidth != this->m_frameWidth || pixelHeight != this->m_frameHeight)
	{
		this->m_logFileStream << "所有的照片必须使用固定的大小." << endl;
		return E_IMAGESIZEINCORRECT;
	}

	// 创建源位图对象.
	CheckHR(this->m_pIWICFactory->CreateBitmapFromSource(pFrame, WICBitmapCacheOnLoad, &pSourceBitmap));
	this->m_logFileStream << "位图资源创建成功." << endl;

	lockRect.X = 0;
	lockRect.Y = 0;
	lockRect.Width = pixelWidth;
	lockRect.Height = pixelHeight;
	CheckHR(pSourceBitmap->Lock(&lockRect, WICBitmapLockWrite, &pLock));
	UINT sourceBufferSize;
	CheckHR(pLock->GetDataPointer(&sourceBufferSize, &pSourceBuffer));

	// Jpg BGR 位图转换 RGBA 格式.
	UINT destinationBufferSize = sourceBufferSize / 3 * 4;
	pDestinationBuffer = new BYTE[destinationBufferSize];
	for (UINT i = 0, j = 0; i < sourceBufferSize; i+=3, j+=4)
	{
		pDestinationBuffer[j] = pSourceBuffer[i]; // R
		pDestinationBuffer[j + 1] = pSourceBuffer[i + 1]; // G
		pDestinationBuffer[j + 2] = pSourceBuffer[i + 2]; // B
		pDestinationBuffer[j + 3] = 255; // A
	}

	*ppOutputBitmap = pDestinationBuffer;
	*pBitmapSize = destinationBufferSize;

cleanup:
	if (!SUCCEEDED(hr))
	{
		DWORD error = GetLastError();
		this->m_logFileStream << "意外错误: " << error << endl;
		this->m_logFileStream << "HResult是: " << hr << endl;
	}
	if (pSourceBuffer != nullptr)
	{
		// 删除pSourceBuffer;
	}
	SafeRelease(&pDecoder);
	SafeRelease(&pFrame);
	SafeRelease(&pSourceBitmap);
	SafeRelease(&pLock);

	return hr;
}
Example #20
0
unsigned char *BBWin8Game::LoadImageData( String path,int *pwidth,int *pheight,int *pformat ){

	if( !_wicFactory ){
		DXASS( CoCreateInstance( CLSID_WICImagingFactory,0,CLSCTX_INPROC_SERVER,__uuidof(IWICImagingFactory),(LPVOID*)&_wicFactory ) );
	}
	
	path=PathToFilePath( path );

	IWICBitmapDecoder *decoder;
	if( !SUCCEEDED( _wicFactory->CreateDecoderFromFilename( path.ToCString<wchar_t>(),NULL,GENERIC_READ,WICDecodeMetadataCacheOnDemand,&decoder ) ) ){
		return 0;
	}
	
	unsigned char *data=0;

	IWICBitmapFrameDecode *bitmapFrame;
	DXASS( decoder->GetFrame( 0,&bitmapFrame ) );
	
	UINT width,height;
	WICPixelFormatGUID pixelFormat;
	DXASS( bitmapFrame->GetSize( &width,&height ) );
	DXASS( bitmapFrame->GetPixelFormat( &pixelFormat ) );
			
	if( pixelFormat==GUID_WICPixelFormat24bppBGR ){
		unsigned char *t=(unsigned char*)malloc( width*3*height );
		DXASS( bitmapFrame->CopyPixels( 0,width*3,width*3*height,t ) );
		data=(unsigned char*)malloc( width*4*height );
		unsigned char *s=t,*d=data;
		int n=width*height;
		while( n-- ){
			*d++=s[2];
			*d++=s[1];
			*d++=s[0];
			*d++=0xff;
			s+=3;
		}
		free( t );
	}else if( pixelFormat==GUID_WICPixelFormat32bppBGRA ){
		unsigned char *t=(unsigned char*)malloc( width*4*height );
		DXASS( bitmapFrame->CopyPixels( 0,width*4,width*4*height,t ) );
		data=t;
		int n=width*height;
		while( n-- ){	//premultiply alpha
			unsigned char r=t[0];
			t[0]=t[2]*t[3]/255;
			t[1]=t[1]*t[3]/255;
			t[2]=r*t[3]/255;
			t+=4;
		}
	}
	
	if( data ){
		*pwidth=width;
		*pheight=height;
		*pformat=4;
	}
	
	bitmapFrame->Release();
	decoder->Release();
	
	gc_force_sweep=true;

	return data;
}
Example #21
0
HRESULT App::LoadResourceBitmap(
    ID2D1RenderTarget *pRenderTarget,
    IWICImagingFactory *pIWICFactory,
    PCWSTR resourceName,
    PCWSTR resourceType,
    UINT destinationWidth,
    UINT destinationHeight,
    ID2D1Bitmap **ppBitmap
    )
{
    IWICBitmapDecoder *pDecoder = NULL;
    IWICBitmapFrameDecode *pSource = NULL;
    IWICStream *pStream = NULL;
    IWICFormatConverter *pConverter = NULL;
    IWICBitmapScaler *pScaler = NULL;

    HRSRC imageResHandle = NULL;
    HGLOBAL imageResDataHandle = NULL;
    void *pImageFile = NULL;
    DWORD imageFileSize = 0;

    // Locate the resource.
    imageResHandle = FindResourceW(HINST_THISCOMPONENT, resourceName, resourceType);
    HRESULT hr = imageResHandle ? S_OK : E_FAIL;
    if (SUCCEEDED(hr))
    {
        // Load the resource.
        imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle);

        hr = imageResDataHandle ? S_OK : E_FAIL;
    }
    if (SUCCEEDED(hr))
    {
        // Lock it to get a system memory pointer.
        pImageFile = LockResource(imageResDataHandle);

        hr = pImageFile ? S_OK : E_FAIL;
    }
    if (SUCCEEDED(hr))
    {
        // Calculate the size.
        imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle);

        hr = imageFileSize ? S_OK : E_FAIL;
        
    }
    if (SUCCEEDED(hr))
    {
          // Create a WIC stream to map onto the memory.
        hr = pIWICFactory->CreateStream(&pStream);
    }
    if (SUCCEEDED(hr))
    {
        // Initialize the stream with the memory pointer and size.
        hr = pStream->InitializeFromMemory(
            reinterpret_cast<BYTE*>(pImageFile),
            imageFileSize
            );
    }
    if (SUCCEEDED(hr))
    {
        // Create a decoder for the stream.
        hr = pIWICFactory->CreateDecoderFromStream(
            pStream,
            NULL,
            WICDecodeMetadataCacheOnLoad,
            &pDecoder
            );
    }
    if (SUCCEEDED(hr))
    {
        // Create the initial frame.
        hr = pDecoder->GetFrame(0, &pSource);
    }
    if (SUCCEEDED(hr))
    {
        // Convert the image format to 32bppPBGRA
        // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
        hr = pIWICFactory->CreateFormatConverter(&pConverter);
    }
    if (SUCCEEDED(hr))
    {
        // If a new width or height was specified, create an
        // IWICBitmapScaler and use it to resize the image.
        if (destinationWidth != 0 || destinationHeight != 0)
        {
            UINT originalWidth, originalHeight;
            hr = pSource->GetSize(&originalWidth, &originalHeight);
            if (SUCCEEDED(hr))
            {
                if (destinationWidth == 0)
                {
                    FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
                    destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
                }
                else if (destinationHeight == 0)
                {
                    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,
                            WICBitmapInterpolationModeCubic
                            );
                    if (SUCCEEDED(hr))
                    {
                        hr = pConverter->Initialize(
                            pScaler,
                            GUID_WICPixelFormat32bppPBGRA,
                            WICBitmapDitherTypeNone,
                            NULL,
                            0.f,
                            WICBitmapPaletteTypeMedianCut
                            );
                    }
                }
            }
        }
        else
        {
                    
            hr = pConverter->Initialize(
                pSource,
                GUID_WICPixelFormat32bppPBGRA,
                WICBitmapDitherTypeNone,
                NULL,
                0.f,
                WICBitmapPaletteTypeMedianCut
                );
        }
    }
    if (SUCCEEDED(hr))
    {
        //create a Direct2D bitmap from the WIC bitmap.
        hr = pRenderTarget->CreateBitmapFromWicBitmap(
            pConverter,
            NULL,
            ppBitmap
            );
    
    }

    SafeRelease(&pDecoder);
    SafeRelease(&pSource);
    SafeRelease(&pStream);
    SafeRelease(&pConverter);
    SafeRelease(&pScaler);

    return hr;
}
Example #22
0
/// <summary>
/// Tries to set the cover based on the Tags of the specified file.
/// </summary>
/// <param name="filePath">Path to the file to get the cover from.</param>
bool CoverArt::SetCoverFromTag(LPCWSTR filePath)
{
    LPCWSTR extension = wcsrchr(filePath, L'.');

    if (extension == nullptr)
    {
        return false;
    }

    auto ParseImage = [this] (const BYTE * data, UINT size)
    {
        IWICImagingFactory *factory = nullptr;
        IWICBitmapDecoder *decoder = nullptr;
        IWICBitmapFrameDecode *source = nullptr;
        HRESULT hr = E_FAIL;

        IStream *stream = SHCreateMemStream(data, size);
        if (stream)
        {
            hr = Factories::GetWICFactory(reinterpret_cast<LPVOID*>(&factory));
            if (SUCCEEDED(hr))
            {
                hr = factory->CreateDecoderFromStream(stream, nullptr, WICDecodeMetadataCacheOnDemand, &decoder);
            }
            if (SUCCEEDED(hr))
            {
                hr = decoder->GetFrame(0, &source);
            }
            if (SUCCEEDED(hr))
            {
                SendMessage(gLSModule.GetMessageWindow(), WM_COVERARTUPDATE, (WPARAM)this, (LPARAM)source);
            }

            SAFERELEASE(decoder);
            SAFERELEASE(stream);
        }

        return hr == S_OK;
    };

    ++extension;

    if (_wcsicmp(extension, L"mp3") == 0)
    {
        TagLib::ID3v2::AttachedPictureFrame *pictureFrame = nullptr;
        BYTE picturePriority = 0xFF;

        TagLib::MPEG::File mp3File(filePath);
        auto tag = mp3File.ID3v2Tag();

        if (tag && tag->frameListMap().contains("APIC"))
        {
            for (auto frame : mp3File.ID3v2Tag()->frameListMap()["APIC"])
            {
                auto picFrame = (TagLib::ID3v2::AttachedPictureFrame *)frame;

                BYTE priority = mID3CoverTypePriority[picFrame->type()];
                if (priority < picturePriority)
                {
                    pictureFrame = picFrame;
                    picturePriority = priority;
                }
            }
            if (pictureFrame != nullptr) {
                return ParseImage((const BYTE *)pictureFrame->picture().data(), pictureFrame->picture().size());
            }
        }
    }
    else if (_wcsicmp(extension, L"flac") == 0)
    {
        TagLib::FLAC::File flacFile(filePath);
        for (auto &picture : flacFile.pictureList())
        {
            if (picture->type() == TagLib::FLAC::Picture::FrontCover)
            {
                return ParseImage((const BYTE *)picture->data().data(), picture->data().size());
            }
        }
    }
    else if (_wcsicmp(extension, L"mp4") == 0 || _wcsicmp(extension, L"m4a") == 0)
    {
        TagLib::MP4::File mp4File(filePath);
        if (mp4File.tag()->itemListMap().contains("covr"))
        {
            auto map = mp4File.tag()->itemListMap()["covr"];
            auto list = map.toCoverArtList();
            auto cover = list.front();
            return ParseImage((const BYTE *)cover.data().data(), cover.data().size());
        }
    }

    return false;
}
Example #23
0
void PngViewer::load_png_with_wic()
{
	static const D2D1_FACTORY_OPTIONS options = { D2D1_DEBUG_LEVEL_INFORMATION };
	D2D1_BITMAP_PROPERTIES1 bmp_properties;
	ID2D1Factory2 * d2_factory;
	ID2D1Device1 * d2_device;
	ID2D1DeviceContext1 * context;
	IDXGISurface2 * surface;
	IWICBitmapDecoder * decoder;
	IWICBitmapFrameDecode * frame_decoder;
	IWICFormatConverter * format_converter;
	ID2D1Bitmap1 * png_texture;
	ID2D1Bitmap1 * bitmap;

	if(this->wic_factory->CreateDecoderFromFileHandle(reinterpret_cast<ULONG_PTR>(this->png_file_handle), nullptr, WICDecodeMetadataCacheOnLoad, &decoder) != S_OK)
	{
		return;
	}

	if(decoder->GetFrame(0, &frame_decoder) != S_OK)
	{
		decoder->Release();
		return;
	}

	if(this->wic_factory->CreateFormatConverter(&format_converter) != S_OK)
	{
		frame_decoder->Release();
		decoder->Release();
		return;
	}

	format_converter->Initialize(frame_decoder, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.0, WICBitmapPaletteTypeMedianCut);

	frame_decoder->Release();
	decoder->Release();

	if(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, options, &d2_factory) != S_OK)
	{
		format_converter->Release();
		return;
	}

	if(d2_factory->CreateDevice(this->device_gi, &d2_device) != S_OK)
	{
		format_converter->Release();
		d2_factory->Release();
		return;
	}

	if(d2_device->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &context) != S_OK)
	{
		format_converter->Release();
		d2_device->Release();
		d2_factory->Release();
		return;
	}

	if(this->swap_chain->GetBuffer(0, __uuidof(IDXGISurface2), (void **)&surface) != S_OK)
	{
		format_converter->Release();
		context->Release();
		d2_device->Release();
		d2_factory->Release();
		return;
	}

	::memset(&bmp_properties, 0, sizeof(D2D1_BITMAP_PROPERTIES1));
	bmp_properties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
	bmp_properties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
	bmp_properties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW;
	if(context->CreateBitmapFromDxgiSurface(surface, &bmp_properties, &bitmap) != S_OK)
	{
		format_converter->Release();
		surface->Release();
		context->Release();
		d2_device->Release();
		d2_factory->Release();
		return;
	}

	bmp_properties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET;
	if(context->CreateBitmapFromWicBitmap(format_converter, &bmp_properties, &png_texture) != S_OK)
	{
		format_converter->Release();
		bitmap->Release();
		surface->Release();
		context->Release();
		d2_device->Release();
		d2_factory->Release();
		return;
	}

	context->SetTarget(bitmap);
	bitmap->CopyFromBitmap(nullptr, png_texture, nullptr);
	this->swap_chain->Present(1, 0);

	format_converter->Release();
	png_texture->Release();
	bitmap->Release();
	surface->Release();
	context->Release();
	d2_device->Release();
	d2_factory->Release();
}
Example #24
0
// =========================================================
// Load the specified bitmap from file into D2D bitmap
// =========================================================
BOOL Loader::LoadBitmapFromResource(LPCWSTR resourceId, LPCWSTR resourceType, const Graphics* graphicsWrapper, ID2D1Bitmap** ppBitmap)
{
	if (!isInitialized)
		return FALSE;

	HRESULT hr;

	IWICStream *pStream = NULL;
	IWICBitmapDecoder *pDecoder = NULL;
	IWICBitmapFrameDecode *pSource = NULL;
	IWICFormatConverter *pConverter = NULL;

	HRSRC imageResHandle = NULL;
	HGLOBAL imageResDataHandle = NULL;
	void *pImageFile = NULL;
	DWORD imageFileSize = 0;

	HMODULE module = GetModuleHandle(0);

	// Locate the resource
	imageResHandle = FindResource(module, resourceId, resourceType);
	if (!imageResHandle)
	{
		OutputDebugStringA("Loader::LoadBitmapFromResource -> Failed to locate resource.\n");
		return FALSE;
	}

	imageResDataHandle = LoadResource(module, imageResHandle);
	if (!imageResDataHandle)
	{
		OutputDebugStringA("Loader::LoadBitmapFromResource -> Failed to load resource.\n");
		return FALSE;
	}

	// lock resource to get pointer to data
	pImageFile = LockResource(imageResDataHandle);
	if (!pImageFile)
	{
		OutputDebugStringA("Loader::LoadBitmapFromResource -> Failed to lock resource for processing.\n");
		return FALSE;
	}

	// get the size of the image
	imageFileSize = SizeofResource(module, imageResHandle);
	if (!imageFileSize)
	{
		OutputDebugStringA("Loader::LoadBitmapFromResource -> Failed to obtain size of image resource.\n");
		return FALSE;
	}

	// now that we have everything, we create the stream
	hr = pFactory->CreateStream(&pStream);
	CHECK(failedCreateStream);

	// initialise the stream
	hr = pStream->InitializeFromMemory((byte*)pImageFile, imageFileSize);
	CHECK(failedStreamInit);

	hr = pFactory->CreateDecoderFromStream(pStream, NULL, WICDecodeMetadataCacheOnDemand, &pDecoder);
	CHECK(failedDecoder);

	hr = pDecoder->GetFrame(0, &pSource);
	CHECK(failedGetFrame);

	hr = pFactory->CreateFormatConverter(&pConverter);
	CHECK(failedConverter);

	hr = pConverter->Initialize(pSource, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeMedianCut);
	CHECK(failedConversion);

	hr = graphicsWrapper->pRenderTarget->CreateBitmapFromWicBitmap(pConverter, ppBitmap);
	CHECK(failedBitmap);

	return TRUE;
	
failedBitmap:
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create bitmap.\n");
failedConversion:
	pConverter->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to initialise format converter.\n");
failedConverter:
	pSource->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create format converter.\n");
failedGetFrame:
	pDecoder->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to get frame 0 from source bitmap.\n");
failedDecoder:
	pStream->Release();
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create bitmap decoder.\n");
	return FALSE;
failedStreamInit:
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to initialize WIC stream.\n");
	return FALSE;
failedCreateStream:
	OutputDebugStringA("Loader::LoadBitmapFromFile -> Failed to create WIC stream.\n");
	return FALSE;
}
/// <summary>
/// Load an image from a resource into a buffer
/// </summary>
/// <param name="resourceName">name of image resource to load</param>
/// <param name="resourceType">type of resource to load</param>
/// <param name="nOutputWidth">width (in pixels) of scaled output bitmap</param>
/// <param name="nOutputHeight">height (in pixels) of scaled output bitmap</param>
/// <param name="pOutputBuffer">buffer that will hold the loaded image</param>
/// <returns>S_OK on success, otherwise failure code</returns>
HRESULT CCoordinateMappingBasics::LoadResourceImage(PCWSTR resourceName, PCWSTR resourceType, UINT nOutputWidth, UINT nOutputHeight, RGBQUAD* pOutputBuffer)
{
    IWICImagingFactory* pIWICFactory = NULL;
    IWICBitmapDecoder* pDecoder = NULL;
    IWICBitmapFrameDecode* pSource = NULL;
    IWICStream* pStream = NULL;
    IWICFormatConverter* pConverter = NULL;
    IWICBitmapScaler* pScaler = NULL;

    HRSRC imageResHandle = NULL;
    HGLOBAL imageResDataHandle = NULL;
    void *pImageFile = NULL;
    DWORD imageFileSize = 0;

    HRESULT hrCoInit = CoInitialize(NULL);
    HRESULT hr = hrCoInit;

    if (SUCCEEDED(hr))
    {
        hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pIWICFactory);
    }

    if (SUCCEEDED(hr))
    {
        // Locate the resource
        imageResHandle = FindResourceW(HINST_THISCOMPONENT, resourceName, resourceType);
        hr = imageResHandle ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Load the resource
        imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle);
        hr = imageResDataHandle ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Lock it to get a system memory pointer.
        pImageFile = LockResource(imageResDataHandle);
        hr = pImageFile ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Calculate the size.
        imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle);
        hr = imageFileSize ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Create a WIC stream to map onto the memory.
        hr = pIWICFactory->CreateStream(&pStream);
    }

    if (SUCCEEDED(hr))
    {
        // Initialize the stream with the memory pointer and size.
        hr = pStream->InitializeFromMemory(
            reinterpret_cast<BYTE*>(pImageFile),
            imageFileSize);
    }

    if (SUCCEEDED(hr))
    {
        // Create a decoder for the stream.
        hr = pIWICFactory->CreateDecoderFromStream(
            pStream,
            NULL,
            WICDecodeMetadataCacheOnLoad,
            &pDecoder);
    }

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

    if (SUCCEEDED(hr))
    {
        // Convert the image format to 32bppPBGRA
        // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
        hr = pIWICFactory->CreateFormatConverter(&pConverter);
    }

    if (SUCCEEDED(hr))
    {
        hr = pIWICFactory->CreateBitmapScaler(&pScaler);
    }

    if (SUCCEEDED(hr))
    {
        hr = pScaler->Initialize(
            pSource,
            nOutputWidth,
            nOutputHeight,
            WICBitmapInterpolationModeCubic
            );
    }

    if (SUCCEEDED(hr))
    {
        hr = pConverter->Initialize(
            pScaler,
            GUID_WICPixelFormat32bppPBGRA,
            WICBitmapDitherTypeNone,
            NULL,
            0.f,
            WICBitmapPaletteTypeMedianCut);
    }

    UINT width = 0;
    UINT height = 0;
    if (SUCCEEDED(hr))
    {
        hr = pConverter->GetSize(&width, &height);
    }

    // make sure the image scaled correctly so the output buffer is big enough
    if (SUCCEEDED(hr))
    {
        if ((width != nOutputWidth) || (height != nOutputHeight))
        {
            hr = E_FAIL;
        }
    }

    if (SUCCEEDED(hr))
    {
        hr = pConverter->CopyPixels(NULL, width * sizeof(RGBQUAD), nOutputWidth * nOutputHeight * sizeof(RGBQUAD), reinterpret_cast<BYTE*>(pOutputBuffer));
    }

    SafeRelease(pScaler);
    SafeRelease(pConverter);
    SafeRelease(pSource);
    SafeRelease(pDecoder);
    SafeRelease(pStream);
    SafeRelease(pIWICFactory);

    if (SUCCEEDED(hrCoInit))
    {
        CoUninitialize();
    }

    return hr;
}
Example #26
0
HRESULT CRMTexture::Create( std::wstring path )
{
	IWICImagingFactory*	imageFactory = CRMTextureManager::GetInstance()->GetImageFactory();
	IWICBitmapDecoder* bitmapDecoder = nullptr;
	HRESULT hr = S_OK;

	// 디코더 생성
	hr = imageFactory->CreateDecoderFromFilename( path.c_str(), nullptr, GENERIC_READ, 
		WICDecodeMetadataCacheOnDemand, &bitmapDecoder );

	if(FAILED(hr))
		return hr;

	// 디코더에서 프레임 추출
	IWICBitmapFrameDecode* bitmapFrameDecode = nullptr;
	hr = bitmapDecoder->GetFrame( 0, &bitmapFrameDecode );
	
	if(FAILED(hr))
	{
		SafeRelease(bitmapDecoder);
		return hr;
	}

	IWICFormatConverter*	formatConverter = nullptr;

	// 프레임을 기반으로 컨버터 생성
	hr = imageFactory->CreateFormatConverter( &formatConverter );

	if(FAILED(hr))
	{
		SafeRelease(bitmapFrameDecode);
		SafeRelease(bitmapDecoder);
		return hr;
	}

	hr = formatConverter->Initialize( bitmapFrameDecode, 
									GUID_WICPixelFormat32bppPBGRA,
									WICBitmapDitherTypeNone, nullptr, 0.0f,
									WICBitmapPaletteTypeCustom );

	if(FAILED(hr))
	{
		SafeRelease(bitmapFrameDecode);
		SafeRelease(bitmapDecoder);
	}

	hr = CRMRender::GetInstance()->GetRenderTarget()->CreateBitmapFromWicBitmap(formatConverter, nullptr, &m_D2D1Bitmap);
	
	if(FAILED(hr))
	{
		SafeRelease(bitmapFrameDecode);
		SafeRelease(bitmapDecoder);
	}

	m_Width = m_D2D1Bitmap->GetSize().width;
	m_Height = m_D2D1Bitmap->GetSize().height;

	SafeRelease( bitmapFrameDecode );
	SafeRelease( bitmapDecoder );

	return hr;
}
Example #27
0
	HBITMAP ImageUtil::LoadImage(string path) {
		size_t pathFileExtDot = path.find_last_of('.');
		if (pathFileExtDot == string::npos || pathFileExtDot + 1 >=
			path.length())
			throw INETRException("[imgLoadFailed]");
		string ext = path.substr(pathFileExtDot + 1);

		const GUID *decoderCLSID = nullptr;
		if (ext == "png")
			decoderCLSID = &CLSID_WICPngDecoder;
		else if (ext == "bmp")
			decoderCLSID = &CLSID_WICBmpDecoder;
		else if (ext == "gif")
			decoderCLSID = &CLSID_WICGifDecoder;
		else if (ext == "jpg" || ext == "jpeg")
			decoderCLSID = &CLSID_WICJpegDecoder;

		if (decoderCLSID == nullptr)
			throw INETRException("[unsupportedImg]: " + ext);

		IStream *pngFileStream;
		if (FAILED(SHCreateStreamOnFile(path.c_str(), STGM_READ,
			&pngFileStream)))
			throw INETRException("[imgLoadFailed]:\n" + path);

		IWICBitmapDecoder *bmpDecoder = nullptr;
		if (FAILED(CoCreateInstance(*decoderCLSID, nullptr,
			CLSCTX_INPROC_SERVER, __uuidof(bmpDecoder),
			reinterpret_cast<void**>(&bmpDecoder))))
			throw INETRException("[imgDecFailed]");

		if (FAILED(bmpDecoder->Initialize(pngFileStream,
			WICDecodeMetadataCacheOnLoad))) {

			bmpDecoder->Release();
			throw INETRException("[imgDecFailed]");
		}

		UINT bmpFrameCount = 0;
		if (FAILED(bmpDecoder->GetFrameCount(&bmpFrameCount)) && bmpFrameCount
			!= 1) {

			bmpDecoder->Release();
			throw INETRException("[imgDecFailed]");
		}

		IWICBitmapFrameDecode *bmpFrame = nullptr;
		if (FAILED(bmpDecoder->GetFrame(0, &bmpFrame))) {
			bmpDecoder->Release();
			throw INETRException("[imgDecFailed]");
		}

		IWICBitmapSource *bmpSource = nullptr;
		WICConvertBitmapSource(GUID_WICPixelFormat32bppPBGRA, bmpFrame,
			&bmpSource);

		bmpFrame->Release();
		bmpDecoder->Release();

		UINT width = 0, height = 0;
		if (FAILED(bmpSource->GetSize(&width, &height)) || width == 0 || height
			== 0)
			throw INETRException("[imgDecFailed]");

		BITMAPINFO bmInfo;
		ZeroMemory(&bmInfo, sizeof(bmInfo));
		bmInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		bmInfo.bmiHeader.biWidth = width;
		bmInfo.bmiHeader.biHeight = -((LONG)height);
		bmInfo.bmiHeader.biPlanes = 1;
		bmInfo.bmiHeader.biBitCount = 32;
		bmInfo.bmiHeader.biCompression = BI_RGB;

		HBITMAP hbmp = nullptr;

		void *imageBits = nullptr;
		HDC screenDC = GetDC(nullptr);
		hbmp = CreateDIBSection(screenDC, &bmInfo, DIB_RGB_COLORS, &imageBits,
			nullptr, 0);
		ReleaseDC(nullptr, screenDC);
		if (hbmp == nullptr)
			throw INETRException("[imgDecFailed]");

		const UINT bmpStride = width * 4;
		const UINT bmpSize = bmpStride * height;
		if (FAILED(bmpSource->CopyPixels(nullptr, bmpStride, bmpSize,
			static_cast<BYTE*>(imageBits)))) {

			DeleteObject(hbmp);
			hbmp = nullptr;
			throw INETRException("[imgDecFailed]");
		}

		bmpSource->Release();

		return hbmp;
	}
ID2D1Bitmap * BaseButton::LoadBitmap(wchar_t* sz_path)
{
	ID2D1Bitmap *p_bmp=NULL;
	IWICBitmapDecoder *pDecoder = NULL;
	IWICBitmapFrameDecode *pSource = NULL;
	IWICStream *pStream = NULL;
	IWICFormatConverter *pConverter = NULL;
	IWICBitmapScaler *pScaler = NULL;
	HRESULT hr;
	hr = g_pIWICFactory->CreateDecoderFromFilename(sz_path,NULL,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&pDecoder);
	if (SUCCEEDED(hr))
	{
		// Create the initial frame.
		hr = pDecoder->GetFrame(0, &pSource);
	}
	
	if (SUCCEEDED(hr))
	{
		// Convert the image format to 32bppPBGRA
		// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
		hr = g_pIWICFactory->CreateFormatConverter(&pConverter);
	}
	if (SUCCEEDED(hr))
	{
		// If a new width or height was specified, create an
		// IWICBitmapScaler and use it to resize the image.
		UINT originalWidth, originalHeight;
		hr = pSource->GetSize(&originalWidth, &originalHeight);
	}
	if (SUCCEEDED(hr))
	{

		hr =g_pIWICFactory->CreateBitmapScaler(&pScaler);
	}
	if (SUCCEEDED(hr))
	{
		hr = pScaler->Initialize(pSource,50,30,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 =m_pRenderTarget->CreateBitmapFromWicBitmap(pConverter,NULL,&p_bmp);
	}
	
	
	SafeRelease(&pDecoder);
	SafeRelease(&pSource);
	SafeRelease(&pStream);
	SafeRelease(&pConverter);
	SafeRelease(&pScaler);
// 	if (SUCCEEDED(hr))
// 	{
// 		return TRUE;
// 	}
// 	else
// 		return FALSE;
	return p_bmp;
}
Example #29
0
    //@https://msdn.microsoft.com/de-de/library/windows/desktop/dd756686(v=vs.85).aspx
    HRESULT BitmapDecoder::LoadBitmapFromFile(ID2D1RenderTarget * pRenderTarget, PCWSTR uri, ID2D1Bitmap ** ppBitmap)
    {

      IWICImagingFactory* pFactory;


      HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IWICImagingFactory,
        (LPVOID*)&pFactory
      );



      //IWICStream *pStream = NULL; //?

      //IWICBitmapScaler *pScaler = NULL; //?

      IWICBitmapDecoder *pDecoder = NULL;
      if (SUCCEEDED(hr))
      {
        hr = pFactory->CreateDecoderFromFilename(uri, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &pDecoder);
      }
      IWICBitmapFrameDecode *pSource = NULL;
      if (SUCCEEDED(hr))
      {
        hr = pDecoder->GetFrame(0, &pSource);
      }

      IWICFormatConverter *pConverter = NULL;
      if (SUCCEEDED(hr))
      {
        hr = pFactory->CreateFormatConverter(&pConverter);
      }

      if (SUCCEEDED(hr))
      {
        hr = pConverter->Initialize(
          pSource,
          GUID_WICPixelFormat32bppPBGRA,
          WICBitmapDitherTypeNone,
          NULL,
          0.f,
          WICBitmapPaletteTypeMedianCut
        );
      }

      if (SUCCEEDED(hr))
      {
        pRenderTarget->CreateBitmapFromWicBitmap(pConverter, NULL, ppBitmap);
      }
      if (pDecoder != nullptr)
      {
        pDecoder->Release();//SafeRelease(&pDecoder);
      }
      if (pSource != nullptr)
      {
        pSource->Release();
      }
      //SafeRelease(&pSource);
     // pStream->Release();//SafeRelease(&pStream);
      if(pConverter!= nullptr)
      {
        pConverter->Release();
      }
      //SafeRelease(&pConverter);
     // pScaler->Release();//SafeRelease(&pScaler);
      if (pFactory != nullptr)
      {
        pFactory->Release();
      }

      return hr;
    }
Example #30
0
HRESULT LoadBitmapFromFile(
	PCWSTR uri,
	UINT dweight,
	UINT dheight,
	ID2D1Bitmap **bitmap
	)
{
	HRESULT hr = S_OK;
	IWICImagingFactory* pWICFactory = NULL;
	IWICBitmapDecoder* pDecoder = NULL;
	IWICBitmapScaler* pScaler = NULL;
	IWICBitmapFrameDecode* pSource = NULL;
	IWICFormatConverter* pConverter = NULL;
	hr = CoCreateInstance(
		CLSID_WICImagingFactory,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IWICImagingFactory,
		(LPVOID*)&pWICFactory);
	if (SUCCEEDED(hr))
	{
		hr = pWICFactory->CreateDecoderFromFilename(
			uri,
			NULL,
			GENERIC_READ,
			WICDecodeMetadataCacheOnLoad,
			&pDecoder);
	}
	if (SUCCEEDED(hr))
	{
		hr = pDecoder->GetFrame(0, &pSource);
	}
	if (SUCCEEDED(hr))
	{
		hr = pWICFactory->CreateFormatConverter(&pConverter);
	}
	if (SUCCEEDED(hr))
	{
		UINT oWeight, oHeight;
		hr = pSource->GetSize(&oWeight, &oHeight);
		if (SUCCEEDED(hr))
		{
			hr = pWICFactory->CreateBitmapScaler(&pScaler);
			if (SUCCEEDED(hr))
			{
				hr = pScaler->Initialize(
					pSource,
					dweight,
					dheight,
					WICBitmapInterpolationModeCubic);
			}

			if (SUCCEEDED(hr))
			{
				hr = pConverter->Initialize(
					pScaler,
					GUID_WICPixelFormat32bppPBGRA,
					WICBitmapDitherTypeNone,
					NULL,
					0.f,
					WICBitmapPaletteTypeMedianCut
					);
			}

		}
	}
	if (SUCCEEDED(hr))
	{
		hr = pRT->CreateBitmapFromWicBitmap(pConverter, bitmap);
	}
	Safe_Release(pWICFactory);
	Safe_Release(pDecoder);
	Safe_Release(pScaler);
	Safe_Release(pSource);
	Safe_Release(pConverter);
	return hr;
}