Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

Loading a texture from file post DX11.1?

In 11.1 and later Microsoft removed a lot of helpers for loading textures (fromfile, fromstream etc).

I'm trying to port my code over to 11.2 and everything works fine except for this line :

var texture = Texture2D.FromFile<Texture2D>(device, @"C:\Texture.png");

Now all i could find was guidance telling me to use WIC instead but i can't seem to find anything providing me with a Texture2D that is nearly as versatile (all the samples i found require passing in the pixel format among other things).

I'm looking for a solution that would let me load files (without knowing their format or layout before hand) and get a Texture2D out of it just like FromFile allowed. Is there anything like that or even close? I'm assuming there has to be "something" as they wouldn't just deprecate such a feature if it wasn't superfluous.

Any help is most appreciated.

Edit : I'd like to avoid using the SharpDX.Toolkit too, i'm looking for a raw DirectX / WIC etc solution as i don't want to add a dependency on the Toolkit. I'm however perfectly fine on adding any .net Framework 4.0 or 4.5 assembly as a dependency.

Upvotes: 2

Views: 1726

Answers (2)

xoofx
xoofx

Reputation: 3762

There is no easy solution apart from writing the whole WIC interop yourself. Even if you don't want to use the Toolkit, the source code is available and the class WicHelper.cs responsible for decoding images is fairly easy to adapt.

If you want a very simple solution that doesn't handle all WIC cases (format mappings...etc.), you can have a look at TextureLoader.cs.

Upvotes: 3

G&#225;bor
G&#225;bor

Reputation: 10214

Provided you have both a Texture2D and a WPF BitmapImage lying around, something like this will help:

  var map = device.ImmediateContext.MapSubresource(texture, 0, MapMode.WriteDiscard, MapFlags.None);
  bitmap.CopyPixels(Int32Rect.Empty, map.DataPointer, bitmap.PixelWidth * bitmap.PixelHeight * 4, bitmap.PixelWidth * 4);
  device.ImmediateContext.UnmapSubresource(source, 0);

The function you mention was probably something fairly similar under the hood.

If you're not sure about the bitmap being Bgra, you have to convert it first.

Upvotes: 1

Related Questions