# DirectX11 CreateWICTextureFromMemory Using PNG

I've currently got textures loading using CreateWICTextureFromFile however I'd like a little more control over it, and I'd like to store images in their byte form in a resource loader. Below is just two sets of test code that return two separate results and I'm looking for any insight into a possible solution.

ID3D11ShaderResourceView* srv;

std::basic_ifstream<unsigned char> file("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

unsigned char* buffer = new unsigned char[length];

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), &buffer[0], sizeof(buffer), nullptr, &srv, NULL);


As a return for the above code I get Component not found.

std::ifstream file;

file.open("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

std::vector<char> buffer(length);

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), (const uint8_t*)&buffer[0], sizeof(buffer), nullptr, &srv, NULL);


The above code returns that the image format is unknown.

I'm clearly doing something wrong here, any help is greatly appreciated. Tried finding anything even similar on stackoverflow, and google to no avail.

• That function is from DirectXTK and the source is available at directxtk.codeplex.com/SourceControl/changeset/view/… Have you tried debugging it yourself? – Adam Dec 19 '12 at 23:04
• @Adam, As far down as it will let me. In both situations this is the line in CreateWICTextureFromMemory that it's returning on. hr = pWIC->CreateDecoderFromStream( stream.Get(), 0, WICDecodeMetadataCacheOnDemand, &decoder ); I was hoping someone would see that I'm doing something stupid in the way I'm reading the png in. – seethru Dec 19 '12 at 23:44

Hopefully someone trying to do the same thing will find this solution.

Below is the code I used to solve this problem.

std::basic_ifstream<unsigned char> file("image.png", std::ios::binary);

if (file.is_open())
{
file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

unsigned char* buffer = new unsigned char[length];
file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), &buffer[0], (size_t)length, nullptr, &srv, NULL);
}


The important change being (size_t)length in CreateWICTextureFromMemory

It was indeed a stupid error.

• you can mark your own answer – thumbmunkeys Apr 29 '13 at 12:14