从IDirect3DTexture9生成具有透明度的PNG图像

时间:2018-11-13 18:18:12

标签: c++ textures direct3d directx-9

我对Direct3D还是很陌生,我尝试使用LPDIRECT3DTEXTURE9接口从已经加载的初始化图像生成png图像文件到磁盘。请注意,我要保持所加载图像的透明度。

基本上,我正在创建一个函数,该函数获取文件目标路径的std :: string并从现有LPDIRECT3DTEXTURE9对象获取像素并将其保存到磁盘。

尽管我应该添加一个示例代码来说明如何使用BitMap格式来实现自己的想法。

请注意,此代码有效,但我尝试使用PNG格式执行类似的操作。

int Width = 128;
int Height = 128;
LPDIRECT3DTEXTURE9 m_lpTexture;
LPDIRECT3DDEVICE9 s_lpD3DDev = NULL;
bool SaveToBitmapFile(const std::string & szPath)
{
    LPDIRECT3DSURFACE9 lpSurfSrc = NULL;
    LPDIRECT3DSURFACE9 lpSurfDst = NULL;

    m_lpTexture->GetSurfaceLevel(0, &lpSurfSrc);
    s_lpD3DDev->CreateOffscreenPlainSurface(Width, 
        Height, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &lpSurfDst, NULL);

    if (D3D_OK != 
        D3DXLoadSurfaceFromSurface(lpSurfDst, NULL, NULL, lpSurfSrc,
            NULL, NULL, D3DX_FILTER_TRIANGLE, 0))
    {
        lpSurfDst->Release(); lpSurfDst = NULL;
        lpSurfSrc->Release(); lpSurfSrc = NULL;
    }

    CBitMapFile myBmp;
    myBmp.Create(Width, Height);

    D3DLOCKED_RECT LR;
    lpSurfDst->LockRect(&LR, NULL, 0);
    for (int y = 0; y < Height; y++)
    {
        BYTE* pPixelsSrc = ((BYTE*)LR.pBits) + y * LR.Pitch;
        BYTE* pPixelsDst = (BYTE*)(myBmp.Pixels(0, y));
        for (int x = 0; x < Width; x++)
        {
            pPixelsDst[0] = pPixelsSrc[0];
            pPixelsDst[1] = pPixelsSrc[1];
            pPixelsDst[2] = pPixelsSrc[2];

            pPixelsSrc += 4;
            pPixelsDst += 3;
        }
    }
    lpSurfDst->UnlockRect();

    lpSurfDst->Release(); lpSurfDst = NULL;
    lpSurfSrc->Release(); lpSurfSrc = NULL;

    HANDLE hFile = ::CreateFile(szPath.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    DWORD dwRWC = 0;

    WriteFile(hFile, &myBmp.m_Header, sizeof(myBmp.m_Header), &dwRWC, NULL);
    WriteFile(hFile, &myBmp.m_InfoHeader, sizeof(myBmp.m_InfoHeader), &dwRWC, NULL);

    int iWidth = myBmp.Pitch();
    for (int y = myBmp.m_InfoHeader.biHeight - 1; y >= 0; y--)
        WriteFile(hFile, (BYTE*)myBmp.m_pPixels + y * iWidth, iWidth, &dwRWC, NULL);

    CloseHandle(hFile);
}

根据我的理解,我需要使用

D3DSURFACE_DESC sd;
m_lpTexture->GetLevelDesc(0, &sd);

然后自己生成png的标头?

任何帮助将不胜感激!

谢谢!

0 个答案:

没有答案