SlimDX/DirectX9/C# - How to access pixel-data in a Texture

跟風遠走 提交于 2019-11-30 22:26:09

It's kind of awkward to answer my own question, but after some more digging and by simple trial and error, I found the solution.

At first, I had to change the way I loaded my texture. To prevent it from internally resizing to a Power-of-Two size, I had to use the following method:

Texture texture = Texture.FromFile(_graphicsDevice, [filePath], D3DX.DefaultNonPowerOf2, D3DX.DefaultNonPowerOf2, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, 0);

Note how I specifically specified that the size is Non-Power-of-Two.

Next, there was a mistake in my new texture definition. Instead of specifying 0 levels (and making it auto-generate a MipMap), I had to specify 1 level, like this:

Texture texture2 = new Texture(_graphicsDevice, [sourceWidth], [sourceHeight], 1, surface.Usage, surface.Format, surface.Pool);

After having done that, the for-loop I have in my actual question, works fine:

DataRectangle dataRectangle = texture.LockRectangle(0, LockFlags.None);
SurfaceDescription surface = texture.GetLevelDescription(0);

DataRectangle dataRectangle2 = texture2.LockRectangle(0, LockFlags.None);

for (int y = [sourceX]; y < [sourceHeight]; k++)
{
    for (int x = [sourceY]; x < [sourceWidth]; l++)
    {
        byte[] buffer = new byte[4];
        dataRectangle.Data.Seek((y * dataRectangle.Pitch) + (x * 4), SeekOrigin.Begin);
        dataRectangle.Data.Read(buffer, 0, 4);

        dataRectangle2.Data.Seek(((y - [sourceY]) * dataRectangle2.Pitch) + ((x - [sourceX]) * 4), SeekOrigin.Begin);
        dataRectangle2.Data.Write(buffer, 0, 4);
    }
}

texture.UnlockRectangle(0);
texture2.UnlockRectangle(0);

_graphicsDevice.SetTexture(0, texture2);

Everything in brackets is considered a variable from outside this snippet. I suppose _graphicsDevice is clear enough. I am aware the .Seek can be simplified, but I think it works fine for example purposes. Note that I do not recommended doing this kind of operation every frame, as it drains your FPS quite fast when used wrong.

It took me quite some time to figure it out, but the result is satisfying. I would like to thank everyone who glimpsed over the question and has tried to help me.

Lennard Fonteijn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!