static FtkBitmap* load_win32 (const char *filename)
{
	int x = 0;
	int y = 0;
	int w = 0;
	int h = 0;
	FtkColor bg = {0};
	FtkBitmap* bitmap = NULL;
	WCHAR wfilename[MAX_PATH] = {0};
	mbstowcs(wfilename, filename, MAX_PATH);
	Bitmap* img = Bitmap::FromFile(wfilename);

	return_val_if_fail(img != NULL, NULL);
	if(img->GetWidth() == 0 || img->GetHeight() == 0)
	{
		delete img;

		return NULL;
	}

	w = img->GetWidth();
	h = img->GetHeight();

	bg.a = 0xff;
	bitmap = ftk_bitmap_create(w, h, bg);
	Rect r(0, 0, w, h);
	BitmapData bitmapData;
#ifdef VC6
	img->LockBits(r, ImageLockModeRead, PixelFormat32bppARGB, &bitmapData);
#else
	img->LockBits(&r, ImageLockModeRead, PixelFormat32bppARGB, &bitmapData);
#endif
	FtkColor* src = (FtkColor*)bitmapData.Scan0;
	FtkColor* dst = ftk_bitmap_bits(bitmap);

	for(y = 0; y < h; y++)
	{
		for(x = 0; x < w; x++)
		{
			*dst = *src;
			dst++;
			src++;
		}
	}

	img->UnlockBits(&bitmapData);
	
	delete img;

	return bitmap;
}
Example #2
0
void MarkerTool::createCircle()
{
	using namespace Gdiplus;
	delete[] circleData_;
	circleData_ = 0;
	circleStride_ = 0;
	Bitmap * circle = new Bitmap(penSize_, penSize_, PixelFormat32bppARGB);
	Graphics gr2(circle);
	SolidBrush br(Color(255,255,0));
	gr2.FillEllipse( &br, 0, 0, circle->GetWidth(), circle->GetHeight());

	BitmapData circleData;

	Rect lc(0,0,circle->GetWidth(),circle->GetHeight());
	if ( circle->LockBits(&lc, ImageLockModeRead, PixelFormat32bppARGB, & circleData) == Ok)
	{
		if (circleData.Stride > 0) { 
			circleStride_ = circleData.Stride;
		} else {
			circleStride_ = - circleData.Stride;
		}
		size_t dataSize = circleStride_ * circle->GetHeight();
		circleData_ = new uint8_t[dataSize];
		memcpy(circleData_, circleData.Scan0, dataSize);
		circle->UnlockBits(&circleData);
	}
	
	delete circle;
}
Example #3
0
//=================================================================================
//	GetPictureBuffer
//
//	Overloaded version of the above
//=================================================================================
void PictureHandler::GetPictureBuffer(
	string&			filename,
	UINT*&				imgBuffer,
	int&				width,
	int&				height)
{
	Bitmap* bmp				= Bitmap::FromFile((Narrow2Wide(filename)).c_str());
	BitmapData*	bmpData		= new BitmapData;
	height					= bmp->GetHeight();
	width					= bmp->GetWidth();
	long imgSize			= height*width;
	
	Rect rect(0, 0, width, height);

	bmp->LockBits(
		&rect,
		ImageLockModeWrite,
		PixelFormat32bppARGB,
		bmpData);

	_ASSERT( bmpData->Stride/4 == width );

	if( bmpData->Stride/4 != width )
		return;//picture format may not be 24 bit jpg or bmp type

	imgBuffer = new UINT[imgSize];

	memcpy( imgBuffer, (UINT*)bmpData->Scan0, imgSize*sizeof(UINT) );

	bmp->UnlockBits(bmpData);
}
Example #4
0
//=================================================================================
//	GetPictureBuffer
//
//	Returns a buffer of the picture just opened
//=================================================================================
void PictureHandler::GetPictureBuffer(
	string&				filename,
	vector<UINT>&		imgBuffer,
	int&				width,
	int&				height)
{
	Bitmap* bmp				= Bitmap::FromFile((Narrow2Wide(filename)).c_str());
	BitmapData*	bmpData		= new BitmapData;
	height					= bmp->GetHeight();
	width					= bmp->GetWidth();
	long imgSize			= height*width;
	
	Rect rect(0, 0, width, height);
	bmp->LockBits(
		&rect,
		ImageLockModeWrite,
		PixelFormat32bppARGB,
		bmpData);

	_ASSERT( bmpData->Stride/4 == width );

	imgBuffer.resize(imgSize);

	//memcpy( imgBuffer, (UINT*)bmpData.get()->Scan0, imgSize*sizeof(UINT) );
	UINT* tempBuff = (UINT*)bmpData->Scan0;
	for( int p = 0; p < imgSize; p++ ) imgBuffer[p] = tempBuff[p];

	bmp->UnlockBits(bmpData);
}
Example #5
0
Gdiplus::Bitmap* LoadImageFromFileWithoutLocking(const WCHAR* fileName) {
	using namespace Gdiplus;
	Bitmap src( fileName );
	if ( src.GetLastStatus() != Ok ) {
		return 0;
	}
	Bitmap *dst = new Bitmap(src.GetWidth(), src.GetHeight(), PixelFormat32bppARGB);

	BitmapData srcData;
	BitmapData dstData;
	Rect rc(0, 0, src.GetWidth(), src.GetHeight());

	if (src.LockBits(& rc, ImageLockModeRead, PixelFormat32bppARGB, & srcData) == Ok)
	{
		if ( dst->LockBits(& rc, ImageLockModeWrite, PixelFormat32bppARGB, & dstData) == Ok ) {
			uint8_t * srcBits = (uint8_t *) srcData.Scan0;
			uint8_t * dstBits = (uint8_t *) dstData.Scan0;
			unsigned int stride;
			if (srcData.Stride > 0) { 
				stride = srcData.Stride;
			} else {
				stride = - srcData.Stride;
			}
			memcpy(dstBits, srcBits, src.GetHeight() * stride);

			dst->UnlockBits(&dstData);
		}
		src.UnlockBits(&srcData);
	}
	return dst;
}
Example #6
0
void CRichEditDlg::OnPaint(HDC hPaintDc)
{
	CSysUnit::SetWindowToTransparence(m_hWnd, true);

	CRect WndRect = this->GetClientRect();
	m_BmpDc.Create(WndRect.Width(), WndRect.Height());

	HDC hMemoryDC = m_BmpDc.GetSafeHdc();
	HBITMAP hMemoryBitmap = m_BmpDc.GetBmpHandle();
	if (hMemoryDC != NULL && hMemoryBitmap != NULL)
	{
		Graphics DoGrap(hMemoryDC);

		SolidBrush FillBrush(Color(255, 0, 255, 255));
		DoGrap.FillRectangle(&FillBrush, 0, 0, WndRect.Width(), WndRect.Height());

//////////////////////////////////////////////////////////////////////////

		WndRect = this->GetWindowRect();
		CUiMethod::GetScreenBitmap(hMemoryDC, WndRect);

		// GDI 数据
//		m_GaussB.ImageGaussBlur((BYTE *)m_BmpDc.GetBits(), m_BmpDc.GetDcSize().cx, m_BmpDc.GetDcSize().cy, 6, 30, 6, 6);

		// GDI+ 数据
		Bitmap *ptBmp = Bitmap::FromHBITMAP(hMemoryBitmap, NULL);
		BitmapData LockedBmpData;
		ptBmp->LockBits(Rect(0, 0, m_BmpDc.GetDcSize().cx, m_BmpDc.GetDcSize().cy), ImageLockModeRead | ImageLockModeWrite, PixelFormat32bppARGB, &LockedBmpData);
		m_GaussB.ImageGaussBlur((BYTE *)LockedBmpData.Scan0, m_BmpDc.GetDcSize().cx, m_BmpDc.GetDcSize().cy, 6, 30, 6, 6);
		ptBmp->UnlockBits(&LockedBmpData);
		DoGrap.DrawImage(ptBmp, PointF(0, 0));
		delete ptBmp;

//////////////////////////////////////////////////////////////////////////

		// 开始画图
		m_pUiManager->OnPaint(hMemoryDC, WndRect);

		WndRect = this->GetClientRect();
		DrawFetionBkgndLine(hMemoryDC, WndRect);
		DrawGlassLine(hMemoryDC, m_GlassRect);

		{
			WndRect = this->GetWindowRect();
			POINT ptWinPos = {WndRect.left, WndRect.top};
			POINT ptSrc = {0, 0};
			SIZE sizeWindow = {WndRect.Width(), WndRect.Height()};
			::UpdateLayeredWindow(m_hWnd, hPaintDc, &ptWinPos, &sizeWindow, hMemoryDC, &ptSrc, 0, &m_Blend, ULW_ALPHA);
		}

		{
			//	CSysUnit::SetWindowToTransparence(m_hWnd, false);
			//	::BitBlt(hPaintDc, 0, 0, WndRect.Width(), WndRect.Height(),
			//		hMemoryDC, 0, 0, SRCCOPY);
		}
	}
}
Example #7
0
bool CExampleDemoDlg::GetFaceRect(Bitmap* pImageSori)
{
	//_sleep(100);
	Bitmap* pImageS = pImageSori->Clone(0, 0, pImageSori->GetWidth(), pImageSori->GetHeight(), PixelFormat32bppARGB);
	// TODO:  在此添加您专用的创建代码
	float scalew = 1.;
	if (pImageS->GetWidth() > 480 || pImageS->GetHeight() > 640)
	{

		scalew=min(480.f / pImageS->GetWidth(), 640.f / pImageS->GetHeight());

		int width = pImageS->GetWidth()*scalew;
		int height = pImageS->GetHeight()*scalew;
		ResizeBitmap(&pImageS, width, height);
	}


	Gdiplus::BitmapData TempBitmapData;
	Gdiplus::Rect rc(0, 0, pImageS->GetWidth(), pImageS->GetHeight());
	pImageS->LockBits(&rc, Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, PixelFormat32bppARGB, &TempBitmapData);


	CPupilGUI cpi = CPupilGUI((BYTE*)TempBitmapData.Scan0, TempBitmapData.Width, TempBitmapData.Height);
	pImageS->UnlockBits(&TempBitmapData);
	SAFE_DELETE(pImageS);
	if (cpi.isface == true)
	{
		int x0=cpi.m_face_detection.rFace.left;
		int y0 = cpi.m_face_detection.rFace.top;
		int width = (cpi.m_face_detection.rFace.right-x0)/scalew;
		int height = (cpi.m_face_detection.rFace.bottom-y0)/scalew;
		if (height+width<700)
		{
			return false;
		}
		else
		{
			return true;
		}
		//return GetRect(CRect(x0/scalew, y0/scalew, width/scalew, height/scalew), pImageSori);

	}
	else
	{
		return false;
	}



}
Example #8
0
HRESULT FontSheet::BuildFontSheetTexture(ID3D11Device* device, Bitmap& fontSheetBitmap)
{
	HRESULT hr = S_OK;

	// Lock the bitmap for direct memory access
	BitmapData bmData;
	fontSheetBitmap.LockBits(&Rect(0, 0, mTexWidth, mTexHeight), 
		ImageLockModeRead, PixelFormat32bppARGB, &bmData);  

	// Copy into a texture.
	D3D11_TEXTURE2D_DESC texDesc;
	texDesc.Width  = mTexWidth;
	texDesc.Height = mTexHeight;
	texDesc.MipLevels = 1;
	texDesc.ArraySize = 1;
	texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	texDesc.SampleDesc.Count = 1;
	texDesc.SampleDesc.Quality = 0;
	texDesc.Usage = D3D11_USAGE_IMMUTABLE;
	texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
	texDesc.CPUAccessFlags = 0;
	texDesc.MiscFlags = 0;

	D3D11_SUBRESOURCE_DATA data;        
	data.pSysMem = bmData.Scan0;
	data.SysMemPitch = mTexWidth * 4;
	data.SysMemSlicePitch = 0;

	hr = device->CreateTexture2D(&texDesc, &data, &mFontSheetTex);
	if(FAILED(hr))
		return hr;

	D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
	srvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	srvDesc.Texture2D.MipLevels = 1;
	srvDesc.Texture2D.MostDetailedMip = 0;

	hr = device->CreateShaderResourceView(mFontSheetTex, &srvDesc, &mFontSheetSRV);
	if(FAILED(hr))
		return hr;

	fontSheetBitmap.UnlockBits(&bmData);  

	return hr;
}
Example #9
0
void CBalloonTip::InitIconImage()
{
	HICON hIcon = LoadIcon(CPaintManagerUI::GetResourceDll(),MAKEINTRESOURCE(m_nIcon));
	if (hIcon)
	{
		ICONINFO icInfo = { 0 };
		if (::GetIconInfo(hIcon, &icInfo))
		{
			BITMAP bitmap; 
			GetObject(icInfo.hbmColor, sizeof(BITMAP), &bitmap);

			Bitmap* pBitmap = NULL;
			Bitmap* pWrapBitmap = NULL;
			if (bitmap.bmBitsPixel != 32)
			{   
				pBitmap = Bitmap::FromHICON(hIcon);
			} 
			else
			{
				pWrapBitmap = Bitmap::FromHBITMAP(icInfo.hbmColor, NULL);
				BitmapData bitmapData;
				Rect rcImage(0,0, pWrapBitmap->GetWidth(), pWrapBitmap->GetHeight());
				pWrapBitmap->LockBits(&rcImage, ImageLockModeRead, pWrapBitmap->GetPixelFormat(), &bitmapData); 

				pBitmap = new Bitmap(bitmapData.Width, bitmapData.Height, bitmapData.Stride,  PixelFormat32bppARGB, (BYTE*)bitmapData.Scan0);

				pWrapBitmap->UnlockBits(&bitmapData);
			}

			//lpIconImage = pBitmap->Clone(0, 0, pBitmap->GetWidth(), pBitmap->GetHeight(), PixelFormat32bppARGB);

			HBITMAP hBit ;

			pBitmap->GetHBITMAP(ARGB(0,0,0,0),&hBit);

			m_pPM->AddImage(_T("BalloonIcon"),hBit,pBitmap->GetWidth(),pBitmap->GetHeight(),TRUE);

			DeleteObject(icInfo.hbmColor); 
			DeleteObject(icInfo.hbmMask); 
		}
		DeleteObject(hIcon);
	}
}
Example #10
0
Bitmap* CExampleDemoDlg::GetRect(CRect r,Bitmap* pImageSori)
{
	int a = r.top + r.left;
	int b = r.Height();
	int c = r.Width();
	Gdiplus::BitmapData TempBitmapData_ori;
	Gdiplus::Rect rcori(0, 0, pImageSori->GetWidth(), pImageSori->GetHeight());
	pImageSori->LockBits(&rcori, Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, PixelFormat32bppARGB, &TempBitmapData_ori);
	BYTE*pori= (BYTE*)TempBitmapData_ori.Scan0;



	Bitmap* pImageS = pImageSori->Clone(0, 0, pImageSori->GetWidth(), pImageSori->GetHeight(), PixelFormat32bppARGB);
	ResizeBitmap(&pImageS, r.Width(), r.Height());
	Gdiplus::BitmapData TempBitmapData_scale;
	Gdiplus::Rect rcscale(0, 0, pImageS->GetWidth(), pImageS->GetHeight());
	pImageS->LockBits(&rcscale, Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, PixelFormat32bppARGB, &TempBitmapData_scale);
	BYTE*pscale = (BYTE*)TempBitmapData_scale.Scan0;

	for (int i=0;i<r.Height();i++)
	{
		for (int j = 0; j < r.Width(); j++)
		{
			int posx = r.left+ j;
			int posy = r.top + i;
			int indexori = (posy*TempBitmapData_ori.Width + posx) * 4;
			for (int k=0;k<4;k++)
			{
				pscale[(i*r.Width() + j) * 4+k] = pori[indexori+k];
			}

		}
	}
	pImageS->UnlockBits(&TempBitmapData_scale);
	pImageSori->UnlockBits(&TempBitmapData_ori);

	return  pImageS;
}
Example #11
0
void MarkerTool::highlightRegion(RECT rc)
{
	Bitmap* canvasBm = canvas_->currentDocument()->getBitmap();
	BitmapData canvasData;
	int w = min(canvasBm->GetWidth()-rc.left,rc.right - rc.left);
	int h = min(canvasBm->GetHeight()-rc.top, rc.bottom - rc.top);
	rc.left = max(0,rc.left);
	rc.top = max(0,rc.top);
	Rect rc2 (rc.left , rc.top, w, h);
	segments_.markRect( rc );
	if (canvasBm->LockBits(& rc2, ImageLockModeRead|ImageLockModeWrite, PixelFormat32bppARGB, & canvasData) == Ok) {
		UINT stride;
		uint8_t * source= (uint8_t *) canvasData.Scan0;
		uint8_t * brSource= (uint8_t *) circleData_;
		if (canvasData.Stride > 0) {
			stride = canvasData.Stride;
		} else {
			stride = - canvasData.Stride;
		}
		/*int lum = 0;
		int disp = 0;
		for ( int i =0; i < h; i++ ) {
		for ( int j = 0; j < w; j++ ) {
		int offset = i*stride+j*4;
		int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];
		lum += Y;
		}
		}

		lum = float(lum) / ( w * h);
		for ( int i =0; i < h; i++ ) {
		for ( int j = 0; j < w; j++ ) {
		int offset = i*stride+j*4;
		int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];
		if ( abs(Y-lum) > disp ) {
		disp = abs(Y-lum);
		}
		}
		}*/

		for ( int i =0; i < h; i++ ) {
			for ( int j = 0; j < w; j++ ) {
				/*if ( affectedRegion_.IsVisible(i+rc.top, j+rc.left) ) {
				continue;
				}*/
				int offset = i*stride+j*4;
				int circleOffset = i * circleStride_ + j* 4;
				int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];

				float srcA =  pow(brSource[circleOffset+3]/255.0 * (Y/255.0),15); // why pow 15 ?? I don't know
				uint8_t srcR=  brSource[circleOffset];
				uint8_t srcG=  brSource[circleOffset+1];
				uint8_t srcB=  brSource[circleOffset+2];
				if ( Y != 255 ) {
					srcA = srcA;
				}

				float dstA =  source[offset+3]/255.0;
				uint8_t dstR=  source[offset];
				uint8_t dstG=  source[offset+1];
				uint8_t dstB=  source[offset+2];
				float outA = srcA + dstA*(1-srcA);
				uint8_t outR=  (srcR * srcA + dstR * dstA * ( 1 - srcA))/ outA;
				uint8_t outG=  (srcG * srcA + dstG * dstA* ( 1 - srcA))/ outA;
				uint8_t outB=  (srcB * srcA + dstB * dstA* ( 1 - srcA))/ outA;
				source[offset] = outR;
				source[offset+1] = outG ;
				source[offset+2] = outB;
				source[offset+3] = outA * 255; 

			}
		}

		canvasBm->UnlockBits(&canvasData);
	}

}
Example #12
0
bool RichEditHost::RenderTo(Graphics& graphics, const MiniRect& rcRender)
{
    if (!m_pTextServices || !m_pEdit)
    {
        return false;
    }

    MiniRect rcRootRender = rcRender;
    MiniRect rcRoot;
    m_pEdit->GetClientRect(rcRoot);
    rcRootRender += rcRoot.TopLeft();

    Bitmap* pBitmap = graphics.GetBitmap();
    byte* pBytes = (byte*)pBitmap->LockBits(rcRootRender);
    for (int i = 0; i < rcRender.Height(); ++i)
    {
        MiniARGB* pSrc = (MiniARGB*)(pBytes + i * pBitmap->GetBytesWidth());
        MiniARGB* pDst = (MiniARGB*)(m_dib.GetData() + (i + rcRender.top) * m_dib.GetBytesWidth()) + rcRender.left;
        for (int j = 0; j < rcRender.Width(); ++j)
        {
            uint32 c = gTable[pSrc->alpha];
            pDst->blue = (uint32)(c * (uint32)pSrc->blue + (1 << 23)) >> 24;
            pDst->green = (uint32)(c * (uint32)pSrc->green + (1 << 23)) >> 24;
            pDst->red = (uint32)(c * (uint32)pSrc->red + (1 << 23)) >> 24;
            pDst->alpha = 0xFF;
            pDst++;
            pSrc++;
        }
    }

    RECTL rc = {0, 0, m_size.cx, m_size.cy};
    HRESULT hr = m_pTextServices->TxDraw(DVASPECT_CONTENT, 0, 0, 0, m_dib, 0, &rc, 0, 0, 0, 0, TXTVIEW_ACTIVE);
    if (SUCCEEDED(hr))
    {
        if (m_bFocus && m_bShowCaret && m_bEnableCaret && m_bCaretState && !GetReadOnly())
        {
            if (!m_hCaret)
            {
                ::PatBlt((HDC)m_dib, m_rcCaret.left, m_rcCaret.top, m_rcCaret.Width(), m_rcCaret.Height(), DSTINVERT);
            }
            else
            {
                HDC hdcMem = CreateCompatibleDC((HDC)m_dib);
                HGDIOBJ hOld = ::SelectObject(hdcMem, m_hCaret);    
                ::BitBlt((HDC)m_dib, m_rcCaret.left, m_rcCaret.top, m_rcCaret.Width(), m_rcCaret.Height(), hdcMem, 0, 0, SRCINVERT);
                ::SelectObject(hdcMem, hOld);
                ::DeleteDC(hdcMem);
            }
        }

        for (int i = 0; i < rcRender.Height(); ++i)
        {
            MiniARGB* pSrc = (MiniARGB*)(m_dib.GetData() + (i + rcRender.top) * m_dib.GetBytesWidth()) + rcRender.left;
            MiniARGB* pDst = (MiniARGB*)(pBytes + i * pBitmap->GetBytesWidth());
            for (int j = 0; j < rcRender.Width(); ++j)
            {
                uint32 alpha = (uint32)pDst->alpha + 1;
                pDst->blue = ((uint32)pSrc->blue * alpha) >> 8;
                pDst->green = ((uint32)pSrc->green * alpha) >> 8;
                pDst->red = ((uint32)pSrc->red * alpha) >> 8;
                pDst++;
                pSrc++;
            }
        }
    }

    return true;
}
Example #13
0
void MainWindow::saveToFile() {
	std::ofstream outFile(mOutFile, std::ios::binary);
	std::stringstream out;
	uint32 signature = 'FNTI';
	out.write((const char*)&signature, sizeof(uint32));
	
	struct FNTIHeader
	{
		uint32 numPages;
		uint32 ofsPages;
	} header;

	header.numPages = mActiveBlocks.size();
	header.ofsPages = sizeof(FNTIHeader) + sizeof(uint32);
	out.write((const char*)&header, sizeof(FNTIHeader));

	struct FNTIBlockDesc
	{
		uint32 id;
		uint32 numChars;
		uint32 ofsChars;
		uint32 bmpWidth;
		uint32 bmpHeight;
		uint32 ofsBmp;
		wchar_t minChar;
		wchar_t maxChar;
		wchar_t pageName[64];
	};

	std::vector<FNTIBlockDesc> descriptions(mActiveBlocks.size());

	uint32 counter = 0;
	for(auto& block : mActiveBlocks) {
		FNTIBlockDesc desc;
		memset(&desc, 0, sizeof(desc));
		desc.id = block.id;
		desc.bmpWidth = 256;
		desc.bmpHeight = 256;
		desc.minChar = (wchar_t)block.minChar;
		desc.maxChar = (wchar_t)block.maxChar;
		wcsncpy_s(desc.pageName, block.name->c_str(), 64);
		desc.pageName[63] = L'\0';

		out.write((const char*)&desc, sizeof(desc));
		descriptions[counter++] = desc;
	}

	std::vector<Bitmap*> bitmaps(mActiveBlocks.size());

	Bitmap* tmp = new Bitmap(mFontSize * 2, mFontSize);
	Graphics* gchar = Graphics::FromImage(tmp);
	gchar->SetTextRenderingHint(TextRenderingHintAntiAlias);

	for(uint32 i = 0; i < mActiveBlocks.size(); ++i) {
		auto& desc = descriptions[i];
		desc.ofsChars = (uint32)out.tellp();

		Bitmap* bmp = new Bitmap(256, 256);
		bitmaps[i] = bmp;

		Graphics* g = Graphics::FromImage(bmp);
		g->Clear(Color::Transparent);
		g->SetTextRenderingHint(TextRenderingHintAntiAlias);

		uint32 curW = 0, curH = 0;
	
		for(uint32 j = mActiveBlocks[i].minChar; j < mActiveBlocks[i].maxChar; ++j) {
			char c = (char)j;
			wchar_t wc = (wchar_t)j;

			RectF rcChar;
			g->MeasureString(&wc, 1, mDefFont, PointF(0, 0), &rcChar);
			float width = rcChar.Width;
			if(curW + width > bmp->GetWidth()) {
				curW = 0;
				curH += mFontSize + 3;
			}

			g->DrawString(&wc, 1, mDefFont, PointF((float)curW, (float)curH), mWhiteBrush);

			gchar->Clear(Color::Black);
			gchar->DrawString(&wc, 1, mDefFont, PointF(0, 0), mWhiteBrush);

			Color pxl, pxr;
			uint32 ofsl = 0, ofsr = 0;
			bool lfound = false, rfound = false;

			for(uint32 l = 0; l < mFontSize * 2; ++l) {
				for(uint32 h = 0; h < mFontSize; ++h) {
					uint32 r = (2 * mFontSize - 1) - l;

					if(lfound == false) {
						tmp->GetPixel(l, h, &pxl);
						if(pxl.GetRed() > 5) {
							lfound = true;
							ofsl = l;
						}
					}

					if(rfound == false) {
						tmp->GetPixel(r, h, &pxr);
						if(pxr.GetRed() > 5) {
							rfound = true;
							ofsr = r;
						}
					}

					if(lfound && rfound) {
						break;
					}
				}

				if(lfound && rfound) {
					break;
				}
			}

			if(lfound == false || rfound == false || (ofsl >= ofsr)) {
				continue;
			}

			uint16 chrWidth = ofsr - ofsl + 1;

			float txs = (curW + ofsl) / (float)bmp->GetWidth();
			float txe = (curW + width - ofsr) / (float)bmp->GetWidth();
			float tys = curH / (float)bmp->GetHeight();
			float tye = (curH + mFontSize) / (float)bmp->GetHeight();

			curW += (uint32)ceil(width) + 2;

			++desc.numChars;
			out.write((const char*)&wc, sizeof(wchar_t));
			out.write((const char*)&chrWidth, sizeof(uint16));
			out.write((const char*)&txs, sizeof(float));
			out.write((const char*)&txe, sizeof(float));
			out.write((const char*)&tys, sizeof(float));
			out.write((const char*)&tye, sizeof(float));
		}

		delete g;
	}

	delete gchar;
	delete tmp;

	for(uint32 i = 0; i < mActiveBlocks.size(); ++i) {
		auto& desc = descriptions[i];
		desc.ofsBmp = (uint32)out.tellp();
		Bitmap* bmp = bitmaps[i];
		BitmapData data;
		bmp->LockBits(&Rect(0, 0, bmp->GetWidth(), bmp->GetHeight()), 0, PixelFormat32bppARGB, &data);
		out.write((const char*)data.Scan0, bmp->GetWidth() * bmp->GetHeight());
		bmp->UnlockBits(&data);

		delete bmp;
	}

	out.seekp(header.ofsPages, std::ios::beg);
	out.write((const char*)descriptions.data(), descriptions.size() * sizeof(FNTIBlockDesc));

	out.seekp(0, std::ios::end);

	uint32 end = (uint32)out.tellp();
	out.seekg(0, std::ios::beg);

	std::vector<char> content(end);
	out.read(content.data(), end);

	std::vector<char> compressed(end);
	Utils::ZDeflater defl;
	defl.begin();

	uint32 outPos = 0;
	defl.update(content, compressed, outPos);
	compressed.resize(outPos);

	defl.end();

	outFile.write((const char*)&end, sizeof(uint32));
	outFile.write(compressed.data(), compressed.size());
	outFile.close();
}
Example #14
0
int loadImage(struct textureTableIndexStruct *tti, char *fname)
{
	/* http://msdn.microsoft.com/en-us/library/ms536298(VS.85).aspx   GDI+ Lockbits example - what this function is based on*/
	/* http://www.microsoft.com/downloads/details.aspx?FamilyID=6a63ab9c-df12-4d41-933c-be590feaa05a&DisplayLang=en  GDI+ redistributable download - gdiplus.dll 2MB */
	if(!loaded)
	{
		initImageLoader();
		loaded = 1;
	}
	// convert to wide char http://msdn.microsoft.com/en-us/library/ms235631(VS.80).aspx   
	//fname = "C:/source2/freewrl/freex3d/tests/helpers/brick.png";  
    //fname = "junk.jpg"; //test failure condition
	size_t origsize = strlen(fname) + 1;
	char* fname2 = (char*) malloc(origsize);
	strcpy(fname2,fname);
	for(int jj=0;jj<strlen(fname2);jj++)
		if(fname2[jj] == '/' ) fname2[jj] = '\\';

    const size_t newsize = 225;
    size_t convertedChars = 0;
    wchar_t wcstring[newsize];
    //mbstowcs_s(&convertedChars, wcstring, origsize, fname, _TRUNCATE);
#if _MSC_VER >= 1500
    mbstowcs_s(&convertedChars, wcstring, origsize, fname2, _TRUNCATE);
#else
    mbstowcs(wcstring, fname2, MB_CUR_MAX);
#endif

	free(fname2);
	Bitmap *bitmap = NULL;
	Status stat;
	bitmap = Bitmap::FromFile(wcstring,false); //new Bitmap(wcstring); //or Bitmap::FromFile(wcstring,false); L"LockBitsTest1.bmp");
	// verifying the success of constructors http://msdn.microsoft.com/en-us/library/ms533801(VS.85).aspx

	stat = bitmap->GetLastStatus(); // http://msdn.microsoft.com/en-us/library/ms535410(VS.85).aspx
	if(stat != Ok)
		return 0; //should come here if it can't find the image file
   BitmapData* bitmapData = new BitmapData;

//#define verbose 1
#ifdef verbose
   printf("bitmap W=%d H=%d\n",bitmap->GetWidth(),bitmap->GetHeight());
   /* http://msdn.microsoft.com/en-us/library/ms535387(VS.85).aspx GetPixelFormat
	  http://msdn.microsoft.com/en-us/library/ms534412(v=VS.85).aspx  pixelFormat constants
	  http://msdn.microsoft.com/en-us/library/ms534136(v=VS.85).aspx   Image::GetFlags ImageFlagsColorSpaceGRAY      = 0x0040,

   */
   UINT flags = bitmap->GetFlags();
   printf("The value of flags, in hexadecimal form, is %x.\n", flags);

   // Is the ColorSpaceRGB flag set?
   if(flags & ImageFlagsColorSpaceRGB)
      printf("The ColorSpaceRGB flag is set.\n");
   else if(flags & ImageFlagsColorSpaceGRAY)
     printf("The ColorSpaceGRAY flag is set.\n");
   printf("bitmap format index =%d %d\n",bitmap->GetPixelFormat()%256,bitmap->GetPixelFormat());
   if(Gdiplus::IsAlphaPixelFormat(bitmap->GetPixelFormat()) ) 
	   printf("has alpha channel\n");
   else
	   printf("no alpha channel\n");
   if(Gdiplus::IsCanonicalPixelFormat(bitmap->GetPixelFormat()) )
	   printf("is canonical\n");
   else
	   printf("not canonical\n");
   printf("Number of bits per pixel %d\n",Gdiplus::GetPixelFormatSize(bitmap->GetPixelFormat()));
#endif
#undef verbose
   bool flipVertically = true;
   Rect rect(0,0,bitmap->GetWidth(),bitmap->GetHeight());
   if(flipVertically)
		bitmapData->Stride = -bitmap->GetWidth()*4;
   else
	   bitmapData->Stride = bitmap->GetWidth()*4;
   bitmapData->Width = bitmap->GetWidth();
   bitmapData->Height = bitmap->GetHeight();
   bitmapData->PixelFormat = PixelFormat32bppARGB;
   int totalbytes = bitmap->GetWidth() * bitmap->GetHeight() * 4; //tti->depth;
   unsigned char * blob = (unsigned char*)malloc(totalbytes);
   if(flipVertically)
		bitmapData->Scan0 = &blob[bitmap->GetWidth()*bitmap->GetHeight()*4 + bitmapData->Stride]; 
   else
	   bitmapData->Scan0 = blob;

   // Lock a rectangular portion of the bitmap for reading.
   bitmap->LockBits(
      &rect,
      ImageLockModeRead|ImageLockModeUserInputBuf,
	  PixelFormat32bppARGB, //PixelFormat24bppRGB, 
      bitmapData);

#ifdef verbose
   printf("The stride is %d.\n\n", bitmapData->Stride);
   printf("bitmapData W=%d H=%d\n",bitmapData->Width,bitmapData->Height);
#endif
#ifdef verbose

   // Display the hexadecimal value of each pixel in the 5x3 rectangle.
   UINT* pixels = (UINT*)bitmapData->Scan0;

   for(UINT row = 0; row < 23; ++row)
   {
      for(UINT col = 0; col < 5; ++col)
      {
         printf("%x\n", pixels[row * bitmapData->Stride / 4 + col]);
      }
      printf("- - - - - - - - - - \n");
   }
#endif

   //deep copy data so browser owns it (and does its FREE_IF_NZ) and we can delete our copy here and forget about it
   tti->x = bitmapData->Width;
   tti->y = bitmapData->Height;
   tti->frames = 1;
   tti->texdata = blob; 
   if(!blob)
	   printf("ouch in gdiplus image loader L140 - no image data\n");
   //tti->hasAlpha = Gdiplus::IsAlphaPixelFormat(bitmapData->PixelFormat)?1:0; 
   tti->hasAlpha = Gdiplus::IsAlphaPixelFormat(bitmap->GetPixelFormat())?1:0; 
   //printf("fname=%s alpha=%ld\n",fname,tti->hasAlpha);

#ifdef verbose
   for(UINT row = 0; row < 23; ++row)
   {
      for(UINT col = 0; col < 5; ++col)
      {
         //printf("%x\n", *(UINT*)&(tti->texdata[(row * bitmapData->Stride / 4 + col)*tti->depth]));
         printf("%x\n", *(UINT*)&(tti->texdata[(row * tti->x + col)*4])); //tti->depth]));
      }
      printf("- - - - - - - - - - \n");
   }
#endif

   tti->filename = fname;
  // wrong: tti->status = TEX_NEEDSBINDING; //make this the last thing you set, because another thread is watching ready to bind
   // wrong - let the calling function set the status otherwise textures disappear sometimes


   bitmap->UnlockBits(bitmapData);
   delete bitmapData;
   delete bitmap;
   //shutdownImageLoader();  //we'll keep it loaded
   if(0)
   {
	   shutdownImageLoader();
	   loaded = 0;
   }

   return 1;

}
Example #15
0
Rect ToolFilter::applyFilter(ToolFilter::Info *fi, Rect *clip, bool once)
{
	Core::self->getGui()->setCursor(CURSOR_WAIT);

	int w = (int)( floor(fi->matrix.mxw / 2.0) );
	int h = (int)( floor(fi->matrix.mxh / 2.0) );

	int exw = fi->matrix.mxw + 1;
	int exh = fi->matrix.mxh + 1;

	UINT *src0, *bmp0;
	BitmapData srcData, bmpData;

	Bitmap *src = fi->bmpSource;
	Rect srcRect(0,0,src->GetWidth(),src->GetHeight());

	if( clip == NULL ){
		clip = &srcRect;
	}
	else {
		int maxx = max(clip->X - exw,0);
		int maxy = max(clip->Y - exh,0);
		int ext = 2;

		srcRect = Rect(
			maxx,
			maxy,
			min(clip->Width + ext * exw,(int)src->GetWidth() - maxx),
			min(clip->Height + ext * exh,(int)src->GetHeight() - maxy)
			);
	}

	int bmpWidth = clip->Width;
	int bmpHeight = clip->Height;
	if( fi->smooth == true ){
		bmpWidth += 4 * exw;
		bmpHeight += 4 * exh;
	}

	Bitmap *bmp = new Bitmap(
		bmpWidth,
		bmpHeight,
		src->GetPixelFormat()
		);
	Rect bmpRect(0,0,bmp->GetWidth(),bmp->GetHeight());

	src->LockBits(
			&srcRect,
			ImageLockModeRead,
			src->GetPixelFormat(),
			&srcData
			);
	bmp->LockBits(
			&bmpRect,
			ImageLockModeWrite,
			bmp->GetPixelFormat(),
			&bmpData
			);
	src0 = (UINT *)srcData.Scan0;
	bmp0 = (UINT *)bmpData.Scan0;

	int srcWidth = srcData.Width;
	int srcHeight = srcData.Height;

	for( int x = 0; x < bmpWidth; x++ ){
		for( int y = 0; y < bmpHeight; y++ ){
			bmp0[y * bmpData.Stride / 4 + x] = ToolFilter::filterPixel(fi,&srcData,x,y,w,h); 
		}
	}
	if( fi->edgeTrace == true && fi->filterValue > 0 ){
		ToolFilter::Matrix oldMatrix = fi->matrix;

		fi->matrix = ToolFilter::allocMatrixEdgetrace(fi->filterValue,1);
		for( int x = 0; x < bmpWidth; x++ ){
			for( int y = 0; y < bmpHeight; y++ ){
				bmp0[y * bmpData.Stride / 4 + x] += ToolFilter::filterPixel(fi,&srcData,x,y,w,h); 
			}
		}
		fi->matrix = ToolFilter::allocMatrixEdgetrace(fi->filterValue,2);
		for( int x = 0; x < bmpWidth; x++ ){
			for( int y = 0; y < bmpHeight; y++ ){
				bmp0[y * bmpData.Stride / 4 + x] += ToolFilter::filterPixel(fi,&srcData,x,y,w,h); 
			}
		}

		fi->matrix = oldMatrix;
	}
	src->UnlockBits(&srcData);
	bmp->UnlockBits(&bmpData);

	fi->bmpEffect = bmp;

	int refils = 0;
	switch(fi->filterId){
		case ID_FILTER_SHARPEN:
			if( fi->filterValue > SHARPENMAX/2 )
				refils = fi->filterValue - SHARPENMAX/2;
			break;
		case ID_FILTER_GAUSSIANBLUR:
			if( fi->filterValue > GAUSSMAX )
				refils = fi->filterValue - GAUSSMAX;
			break;
	}
	Bitmap *source = fi->bmpSource;

	if( refils > 0 && once == false ){
		for(int i = 0; i < refils; i++ ){
			fi->bmpSource = fi->bmpEffect;
			fi->bmpEffect = NULL;

			ToolFilter::applyFilter(fi,NULL,true);

			delete fi->bmpSource;
		}
	}
	fi->bmpSource = source;

	Rect gridClip(clip->X,clip->Y,clip->Width,clip->Height);

	clip->X -= exw;
	clip->Y -= exh;

	Core::self->getGui()->setCursor();

	return gridClip;
}
Example #16
0
void Image::writePNG(const char* aFileName)
{
    std::string _fileName(aFileName);

#ifdef _WIN32
	using namespace Gdiplus;

	// Initialize GDI+.
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	CLSID   encoderClsid;
	Status  stat;

	Bitmap *Image = new Bitmap(m_width, m_height, PixelFormat24bppRGB);
	BitmapData data;
	Rect r(0, 0, m_width, m_height);
	Image->LockBits(&r, ImageLockModeWrite, PixelFormat24bppRGB, &data);

	std::vector<vec3f>::const_iterator it = m_bits.begin();
	for(uint y = 0; y < m_height; y++)
	{
		byte* ptr = (byte*)data.Scan0 + data.Stride * y;
		for(uint x = 0; x < m_width; x++)
		{
			vec3f v = *it++;
			v = vec3f::max(vec3f::min(v, vec3f::rep(1)), vec3f::rep(0));
			*ptr++ = (byte)(v.z * 255);
			*ptr++ = (byte)(v.y * 255);
			*ptr++ = (byte)(v.x * 255);
		}
	}

	Image->UnlockBits(&data);

	// Get the CLSID of the PNG encoder.
	GetEncoderClsid(L"image/png", &encoderClsid);

	std::wstring name(_fileName.begin(), _fileName.end());
	stat = Image->Save(name.c_str(), &encoderClsid, NULL);

	delete Image;
	GdiplusShutdown(gdiplusToken);

#else

	std::vector<png_byte> byteData (m_bits.size() * 3);
	std::vector<png_byte>::iterator ptr = byteData.begin();
	for(std::vector<vec3f>::const_iterator it = m_bits.begin(); it != m_bits.end(); it++)
	{
		vec3f v = *it;
		v = vec3f::max(vec3f::min(v, vec3f::rep(1)), vec3f::rep(0));
		*ptr++ = (byte)(v.x * 255);
		*ptr++ = (byte)(v.y * 255);
		*ptr++ = (byte)(v.z * 255);
	}

	std::vector<png_byte*> rowData(m_height);
	for(int i = 0; i < m_height; i++)
		rowData[i] = i * m_width * 3 + &byteData.front();

	/* create file */
	FILE *fp = fopen(_fileName.c_str(), "wb");
	if (!fp)
	  abort_("[write_png_file] File %s could not be opened for writing", _fileName.c_str());


	/* initialize stuff */
	png_structp png_ptr;
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	if (!png_ptr)
		abort_("[write_png_file] png_create_write_struct failed");

	png_infop info_ptr;
	info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
		abort_("[write_png_file] png_create_info_struct failed");

	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[write_png_file] Error during init_io");


	png_init_io(png_ptr, fp);

	/* write header */
	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[write_png_file] Error during writing header");

	png_set_IHDR(png_ptr, info_ptr, m_width, m_height,
		8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

	png_write_info(png_ptr, info_ptr);

	/* write bytes */
	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[write_png_file] Error during writing bytes");

	png_write_image(png_ptr, (png_byte**)&rowData.front());


	/* end write */
	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[write_png_file] Error during end of write");

	png_write_end(png_ptr, NULL);

	fclose(fp);
#endif //_WIN32
}
Example #17
0
void Image::readPNG(const char* aFileName)
{
    std::string _fileName(aFileName);
#ifdef _WIN32
	using namespace Gdiplus;

	// Initialize GDI+.
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	std::wstring name(_fileName.begin(), _fileName.end());
	Bitmap *bmp = new Bitmap(name.c_str(), FALSE);
	m_width = bmp->GetWidth();
	m_height = bmp->GetHeight();
	m_bits.resize(m_width * m_height);

	BitmapData data;
	Rect r(0, 0, m_width, m_height);
	bmp->LockBits(&r, ImageLockModeWrite, PixelFormat24bppRGB, &data);

	std::vector<vec3f>::iterator it = m_bits.begin();
	for(uint y = 0; y < m_height; y++)
	{
		byte* ptr = (byte*)data.Scan0 + data.Stride * y;
		for(uint x = 0; x < m_width; x++)
		{
			vec3f &v = *it++;
			v.z = (float)(*ptr++) / 255.f;
			v.y = (float)(*ptr++) / 255.f;
			v.x = (float)(*ptr++) / 255.f;
		}
	}

	bmp->UnlockBits(&data);
	delete bmp;

	GdiplusShutdown(gdiplusToken);
#else
	png_byte header[8];	// 8 is the maximum size that can be checked

	/* open file and test for it being a png */
	FILE *fp = fopen(_fileName.c_str(), "rb");
	if (!fp)
		abort_("[read_png_file] File %s could not be opened for reading", _fileName.c_str());
	fread(header, 1, 8, fp);
	if (png_sig_cmp(header, 0, 8))
		abort_("[read_png_file] File %s is not recognized as a PNG file", _fileName.c_str());


	/* initialize stuff */
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	if (!png_ptr)
		abort_("[read_png_file] png_create_read_struct failed");

	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
		abort_("[read_png_file] png_create_info_struct failed");

	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[read_png_file] Error during init_io");

	png_init_io(png_ptr, fp);
	png_set_sig_bytes(png_ptr, 8);

	png_read_info(png_ptr, info_ptr);

	m_width = info_ptr->width;
	m_height = info_ptr->height;
	/*color_type = info_ptr->color_type;
	bit_depth = info_ptr->bit_depth;*/

	int number_of_passes = png_set_interlace_handling(png_ptr);
	png_read_update_info(png_ptr, info_ptr);

	std::vector<png_byte> byteData (info_ptr->rowbytes * m_height);
	std::vector<png_byte*> rowData(m_height);
	for(int i = 0; i < m_height; i++)
		rowData[i] = i * info_ptr->rowbytes + &byteData.front();

	/* read file */
	if (setjmp(png_jmpbuf(png_ptr)))
		abort_("[read_png_file] Error during read_image");

	png_read_image(png_ptr, &rowData.front());

	fclose(fp);

	m_bits.resize(m_width * m_height);
	std::vector<vec3f>::iterator it = m_bits.begin();
	for(size_t y = 0; y < m_height; y++)
	{
		png_byte *b = rowData[y];
		for(size_t x = 0; x < m_width; x++)
		{
			vec3f &v = *it++;
			v.z = (float)(*b++) / 255.f;
			v.y = (float)(*b++) / 255.f;
			v.x = (float)(*b++) / 255.f;
			if(info_ptr->channels == 4)
				b++;
		}
	}
#endif //_WIN32

}
HRESULT CustomUiGetPng(LPCWSTR resource_id, IPictureDisp ** result_image, IPictureDisp** result_mask)
{
	HMODULE hModule = AfxGetResourceHandle();
	HRESULT hr = S_OK;

	using namespace Gdiplus;

	PICTDESC pd = {0};
	pd.cbSizeofstruct = sizeof (PICTDESC);
	pd.picType = PICTYPE_BITMAP;

	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;

	gdiplusStartupInput.DebugEventCallback = NULL;
	gdiplusStartupInput.SuppressBackgroundThread = FALSE;
	gdiplusStartupInput.SuppressExternalCodecs = FALSE;
	gdiplusStartupInput.GdiplusVersion = 1;
	GdiplusStartup (&gdiplusToken, &gdiplusStartupInput, NULL);

	HRSRC hResource = FindResource (hModule, resource_id, L"PNG");

	if (!hResource)
		return HRESULT_FROM_WIN32(GetLastError());

	DWORD dwImageSize = SizeofResource (hModule, hResource);

	const void* pResourceData = LockResource (LoadResource(hModule, hResource));
	if (!pResourceData)
		return HRESULT_FROM_WIN32(GetLastError());

	HGLOBAL hBuffer = GlobalAlloc (GMEM_MOVEABLE, dwImageSize);
	if (hBuffer)
	{
		void* pBuffer = GlobalLock (hBuffer);
		if (pBuffer)
		{
			CopyMemory (pBuffer, pResourceData, dwImageSize);

			IStream* pStream = NULL;
			if (::CreateStreamOnHGlobal (hBuffer, FALSE, &pStream) == S_OK)
			{
				Bitmap *bitmap = Bitmap::FromStream (pStream);
				pStream->Release();

				if (bitmap)
				{
					if (result_mask == NULL) // direct support for picture
					{
						bitmap->GetHBITMAP (0, &pd.bmp.hbitmap);
						hr = OleCreatePictureIndirect (&pd, IID_IDispatch, TRUE, (LPVOID*)result_image);
					}
					else	// old version - 2003/2007 - split into picture + mask
					{
						UINT w = bitmap->GetWidth();
						UINT h = bitmap->GetHeight();
						Rect r(0, 0, w, h);

						Bitmap bitmap_rgb(w, h, PixelFormat24bppRGB);
						Bitmap bitmap_msk(w, h, PixelFormat24bppRGB);

						BitmapData argb_bits;
						bitmap->LockBits(&r, ImageLockModeRead, PixelFormat32bppARGB, &argb_bits);

						BitmapData rgb_bits;
						bitmap_rgb.LockBits(&r, ImageLockModeWrite, PixelFormat24bppRGB, &rgb_bits);

						BitmapData msk_bits;
						bitmap_msk.LockBits(&r, ImageLockModeWrite, PixelFormat24bppRGB, &msk_bits);

						for (UINT y = 0; y < h; ++y)
						{
							for (UINT x = 0; x < w; ++x)
							{
								BYTE* idx_argb = 
									static_cast<BYTE*>(argb_bits.Scan0) + (x + y*w) * 4;

								BYTE* idx_rgb = 
									static_cast<BYTE*>(static_cast<BYTE*>(rgb_bits.Scan0) + (x + y*w) * 3);

								BYTE* idx_msk =
									static_cast<BYTE*>(static_cast<BYTE*>(msk_bits.Scan0) + (x + y*w) * 3);


								idx_rgb[0] = idx_argb[0];
								idx_rgb[1] = idx_argb[1];
								idx_rgb[2] = idx_argb[2];

								byte t = (idx_argb[3] < 128) ? 0xFF : 0x00;

								idx_msk[0] = t;
								idx_msk[1] = t;
								idx_msk[2] = t;
							}
						}

						bitmap->UnlockBits(&argb_bits);

						bitmap_rgb.UnlockBits(&rgb_bits);
						bitmap_msk.UnlockBits(&msk_bits);

						bitmap_rgb.GetHBITMAP (0, &pd.bmp.hbitmap);
						hr = OleCreatePictureIndirect (&pd, IID_IDispatch, TRUE, (LPVOID*)result_image);

						bitmap_msk.GetHBITMAP (0, &pd.bmp.hbitmap);
						hr = OleCreatePictureIndirect (&pd, IID_IDispatch, TRUE, (LPVOID*)result_mask);
					}


					delete bitmap;
				}
			}
			GlobalUnlock (pBuffer);
		}
		GlobalFree (hBuffer);
	}

	GdiplusShutdown (gdiplusToken);
	return hr;
}
Example #19
0
TextDisplay::DisplayTexture TextDisplay::createTexture(const char* text)
{
	DisplayTexture displayTex;
	size_t textLen = strlen(text);
	displayTex.text = new char[textLen+1];
	strcpy_s(displayTex.text, textLen+1, text);
	Bitmap* bitmap;
	Gdiplus::Font* font;

	{
		pfc::stringcvt::string_wide_from_utf8 w_text(text);
		StringFormat strFormat;
		strFormat.SetAlignment(StringAlignmentCenter);
		strFormat.SetTrimming(StringTrimmingNone);
		strFormat.SetFormatFlags(StringFormatFlagsNoFitBlackBox |
								 StringFormatFlagsNoWrap |
								 StringFormatFlagsNoClip);
		RectF stringSize(0, 0, 1024, 128);

		{ // calculate Text Size
			Bitmap calcBitmap(5, 5, PixelFormat32bppARGB);
			Graphics graphics(&calcBitmap);

			HDC fontDC = graphics.GetHDC();
			font = new Gdiplus::Font(fontDC, &(cfgTitleFont.get_value()));
			graphics.ReleaseHDC(fontDC);
			if (!font->IsAvailable()){
				delete font;
				font = new Gdiplus::Font(L"Verdana", 8.0f);
			}

			graphics.MeasureString(w_text, -1, font, PointF(), &stringSize);
		}
		// round to multiples of two, so centering is consistent
		stringSize.Width = ceil(stringSize.Width / 2.0f) * 2;
		stringSize.Height = ceil(stringSize.Height);
		displayTex.texWidth  = displayTex.textWidth  = (int)stringSize.Width;
		displayTex.texHeight = displayTex.textHeight = (int)stringSize.Height;
		
		// Make the texture size a power of two
		displayTex.texWidth = 1;
		while (displayTex.texWidth < displayTex.textWidth)
			displayTex.texWidth = displayTex.texWidth << 1;

		displayTex.texHeight = 1;
		while (displayTex.texHeight < displayTex.textHeight)
			displayTex.texHeight = displayTex.texHeight << 1;

		bitmap = new Bitmap(displayTex.texWidth, displayTex.texHeight, PixelFormat32bppARGB);
		Graphics drawer(bitmap);
		drawer.SetTextRenderingHint(TextRenderingHintAntiAliasGridFit);

		Color textColor(255, 255, 255);
		textColor.SetFromCOLORREF(cfgTitleColor);
		SolidBrush textBrush(textColor);
		displayTex.color = cfgTitleColor;

		drawer.DrawString(w_text, -1, font, stringSize, &strFormat, &textBrush);
	}

	{
		bitmap->RotateFlip(RotateNoneFlipY);
		Rect rc(0,0,bitmap->GetWidth(),bitmap->GetHeight());
		BitmapData bitmapData;
		bitmap->LockBits(&rc,ImageLockModeRead,PixelFormat32bppARGB,&bitmapData);

		glGenTextures(1,&displayTex.glTex);
		glBindTexture(GL_TEXTURE_2D, displayTex.glTex);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);

		void* data = bitmapData.Scan0;
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, displayTex.texWidth, displayTex.texHeight, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE,data);

		bitmap->UnlockBits(&bitmapData);

	}
	delete bitmap;
	delete font;

	return displayTex;
}
BOOL SavePngFile(HICON hIcon, LPCSTR strPngFile,int iOutWith = -1,int iOutHeight = -1)
{
	if (hIcon == NULL)
		return FALSE;

	ICONINFO icInfo = { 0 };
	if (!::GetIconInfo(hIcon, &icInfo))
		return FALSE;


	BITMAP bitmap; 
	GetObject(icInfo.hbmColor, sizeof(BITMAP), &bitmap);

	Bitmap* pBitmap = NULL;
	Bitmap* pWrapBitmap = NULL;
	if (bitmap.bmBitsPixel != 32) 
	{   
		pBitmap = Bitmap::FromHICON(hIcon); 
	} 
	else
	{
		pWrapBitmap = Bitmap::FromHBITMAP(icInfo.hbmColor, NULL);
		BitmapData bitmapData;
		Rect rcImage(0,0, pWrapBitmap->GetWidth(), pWrapBitmap->GetHeight());
		pWrapBitmap->LockBits(&rcImage, ImageLockModeRead, pWrapBitmap->GetPixelFormat(), &bitmapData); 

		pBitmap = new Bitmap(bitmapData.Width, bitmapData.Height, bitmapData.Stride, 
			PixelFormat32bppARGB, (BYTE*)bitmapData.Scan0);

		pWrapBitmap->UnlockBits(&bitmapData);

		Gdiplus::Color Bmpcolor;
		BOOL BmpcolorTag=TRUE;
		for (UINT bmpx=0;bmpx<pBitmap->GetWidth();bmpx++)
		{
			for (UINT bmpy=0;bmpy<pBitmap->GetHeight();bmpy++)
			{
				pBitmap->GetPixel(bmpx,bmpy,&Bmpcolor);
				if(Bmpcolor.GetA()!=0)
				{
					BmpcolorTag=FALSE;
					break;	
				}
			}
			if (BmpcolorTag==FALSE)
				break;
		}
		if (BmpcolorTag==TRUE)
		{
			delete pWrapBitmap;
			pWrapBitmap = NULL;
			delete pBitmap;
			pBitmap = NULL;
			pBitmap = Gdiplus::Bitmap::FromHICON(hIcon); 
		} 
	}

	DeleteObject(icInfo.hbmColor); 
	DeleteObject(icInfo.hbmMask);

	static bool GetPngCode = false;
	static CLSID pngid;
	if (!GetPngCode)
	{
		GetPngCode = true;
		GetEncoderClsid(L"image/png", &pngid);
	}

	if (iOutWith !=-1 && iOutHeight!=-1)
	{
		Bitmap *pStretched =  StretchBitmap(pBitmap,128,128);
		if (pStretched)
		{
			delete pBitmap; 
			pBitmap = pStretched;
		}
	}

	_bstr_t bstr(strPngFile);
	wstring wstrPng = (WCHAR*)bstr;
	Gdiplus::Status s = pBitmap->Save(wstrPng.c_str(),&pngid,NULL);
	delete pBitmap; 
	if (pWrapBitmap)
		delete pWrapBitmap;

	DeleteObject(icInfo.hbmColor); 
	DeleteObject(icInfo.hbmMask); 

	if (s==Gdiplus::Ok)
		return TRUE;

	return FALSE;
}