Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8883881
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T20:55:35+00:00 2026-06-14T20:55:35+00:00

I hava some problem with loading textures from directory. Maybe code first: private Texture2D

  • 0

I hava some problem with loading textures from directory. Maybe code first:

private Texture2D LoadTextureStream(string filePath)
{
    Texture2D file = null;
    RenderTarget2D result = null;

    try
    {
        using (System.IO.Stream titleStream = TitleContainer.OpenStream(filePath))
        {
            file = Texture2D.FromStream(GraphicsDevice, titleStream);
        }
    }
    catch
    {
        throw new System.IO.FileLoadException("Cannot load '" + filePath + "' file!");
    }
    PresentationParameters pp = GraphicsDevice.PresentationParameters;
    //Setup a render target to hold our final texture which will have premulitplied alpha values
    result = new RenderTarget2D(GraphicsDevice, file.Width, file.Height, true, pp.BackBufferFormat, pp.DepthStencilFormat);

    GraphicsDevice.SetRenderTarget(result);
    GraphicsDevice.Clear(Color.Black);

    //Multiply each color by the source alpha, and write in just the color values into the final texture
    BlendState blendColor = new BlendState();
    blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;

    blendColor.AlphaDestinationBlend = Blend.Zero;
    blendColor.ColorDestinationBlend = Blend.Zero;

    blendColor.AlphaSourceBlend = Blend.SourceAlpha;
    blendColor.ColorSourceBlend = Blend.SourceAlpha;

    SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);
    spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
    spriteBatch.Draw(file, file.Bounds, Color.White);
    spriteBatch.End();

    //Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
    BlendState blendAlpha = new BlendState();
    blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha;

    blendAlpha.AlphaDestinationBlend = Blend.Zero;
    blendAlpha.ColorDestinationBlend = Blend.Zero;

    blendAlpha.AlphaSourceBlend = Blend.One;
    blendAlpha.ColorSourceBlend = Blend.One;

    spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
    spriteBatch.Draw(file, file.Bounds, Color.White);
    spriteBatch.End();

    //Release the GPU back to drawing to the screen
    GraphicsDevice.SetRenderTarget(null);

    return result as Texture2D;
}

First, texture is loading from stream. Then, I change some blending options to reach behaviour such as in textures loaded by ContentPipeline. Unfortunately, textures obtained in this way, disapear after game window minimizing. I read something about this problem and a lot of things indicates that RenderTarget2D is fault because render target is set to null after all. What should I do to keep permanently my textures?

EDIT – Fixed code

OK, I used 4th option and it’s work perfectly. Here’s fixed code:

private Texture2D LoadTextureStream(string filePath)
{
    Texture2D file = null;
    Texture2D resultTexture;
    RenderTarget2D result = null;

    try
    {
        using (System.IO.Stream titleStream = TitleContainer.OpenStream(filePath))
        {
            file = Texture2D.FromStream(GraphicsDevice, titleStream);
        }
    }
    catch
    {
        throw new System.IO.FileLoadException("Cannot load '" + filePath + "' file!");
    }
    PresentationParameters pp = GraphicsDevice.PresentationParameters;
    //Setup a render target to hold our final texture which will have premulitplied alpha values
    result = new RenderTarget2D(GraphicsDevice, file.Width, file.Height, true, pp.BackBufferFormat, pp.DepthStencilFormat);

    GraphicsDevice.SetRenderTarget(result);
    GraphicsDevice.Clear(Color.Black);

    //Multiply each color by the source alpha, and write in just the color values into the final texture
    BlendState blendColor = new BlendState();
    blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;

    blendColor.AlphaDestinationBlend = Blend.Zero;
    blendColor.ColorDestinationBlend = Blend.Zero;

    blendColor.AlphaSourceBlend = Blend.SourceAlpha;
    blendColor.ColorSourceBlend = Blend.SourceAlpha;

    SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);
    spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
    spriteBatch.Draw(file, file.Bounds, Color.White);
    spriteBatch.End();

    //Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
    BlendState blendAlpha = new BlendState();
    blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha;

    blendAlpha.AlphaDestinationBlend = Blend.Zero;
    blendAlpha.ColorDestinationBlend = Blend.Zero;

    blendAlpha.AlphaSourceBlend = Blend.One;
    blendAlpha.ColorSourceBlend = Blend.One;

    spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
    spriteBatch.Draw(file, file.Bounds, Color.White);
    spriteBatch.End();

    //Release the GPU back to drawing to the screen
    GraphicsDevice.SetRenderTarget(null);

    resultTexture = new Texture2D(GraphicsDevice, result.Width, result.Height);
    Color[] data = new Color[result.Height * result.Width];
    Color[] textureColor = new Color[result.Height * result.Width];

    result.GetData<Color>(textureColor);

    for (int i = 0; i < result.Height; i++)
    {
        for (int j = 0; j < result.Width; j++)
        {
            data[j + i * result.Width] = textureColor[j + i * result.Width];
        }
    }

    resultTexture.SetData(data);

    return resultTexture;
}

Thanks a lot for help!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T20:55:36+00:00Added an answer on June 14, 2026 at 8:55 pm

    This one is starting to drive me insane. I’ve answered this issue so many times. So I will try and make this one definitive.

    This question keeps coming back because – first of all XNA is poorly documented – but also because people keep posting code like this in tutorials and forums and insisting that it’s “ok” because it seems to work… until you minimise the window and all your textures go missing! Plus there’s the misconception that – by doing the work on the GPU – it must be faster (it might not be).


    Here’s what’s happening:

    At the C#/CPU layer, a RenderTarget2D is a Texture2D. The as Texture2D at the end of your method there does precisely nothing. The cast you make could be implicit. The cast makes no changes to the referenced object instance. You could cast it back to a RenderTarget2D and, again, it wouldn’t change the object itself.

    The reason that RenderTarget2D inherits from Texture2D is so that you can pass a render target to any method that expects a texture and have it work correctly. But their underlying functionality has some important differences:

    At the Direct3D/GPU layer, what is happening is that you are receiving a “Device Lost” error, due to the fact that the device context you were using went away (due to the window being minimised – but that is not the only thing that can cause it). This means that you lose all the GPU memory that you were using – including textures and render targets.

    A regular Texture2D (that you load with ContentManager.Load or Texture2D.FromStream, or set up with SetData) maintains a CPU-side copy of the data. So when the device is lost, XNA will automatically re-create the contents of that texture from the CPU-side copy.

    But a RenderTarget2D is kept entirely on the GPU. XNA has no way to recreate it if it goes missing. Getting a CPU-side copy of its contents would require an extremely expensive copy back from the GPU whenever you changed it.


    Here’s how you fix it:

    • Option 1 is to always re-render the contents of the render target at the start of each frame. This is the standard way to use render targets, as you usually have their contents change each frame anyway. Not really applicable to your case.

    • Option 2 is to respond to the RenderTarget2D.ContentLost event by re-creating the contents of the render target. (Alternately: check the IsContentLost flag each frame.)

    • Option 3 is to create a CPU-side copy of the texture. Basically get the data from the render target with GetData. Then create a new Texture2D and set the data onto it with SetData. XNA will then handle the any device loss for you (as described above).

    • Option 4 is to not use a render target at all! Use GetData to get your texture data, perform your transformation in software, and then set it back with SetData. Seeing as texture data is getting copied around anyway – why not do a copy yourself and premultiply it at the same time?

    • Option 5 is to replace FromStream with something that premultiplies as it loads. This is like option 4, but saves you a few copies. Probably overkill.

    • Option 6 is to store your textures in a pre-multiplied format in the first place. Although at this point you may as well be using the content pipeline.

    Personally I would probably choose option 4 for your situation.


    Finally: Don’t forget to call Dispose on any resources (textures, render targets, etc) that you created yourself (with new or FromStream, but not from ContentManager) that you have finished using.

    I notice that, in your code, you’re leaking Texture2D file.


    To save some insanity, I’ll add to my answer a simple, untested method that premultiplies a texture entirely on the CPU:

    public static void PremultiplyTexture(Texture2D texture)
    {
        Color[] buffer = new Color[texture.Width * texture.Height];
        texture.GetData(buffer);
        for(int i = 0; i < buffer.Length; i++)
        {
            buffer[i] = Color.FromNonPremultiplied(
                    buffer[i].R, buffer[i].G, buffer[i].B, buffer[i].A);
        }
        texture.SetData(buffer);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I hava a data window object, in which I am fetching some attributes from
I'm new at Backbone.js.And I hava some problem at this keyworks.I hava a Backbone
i have some small problem. I hava some class Processor and Process . Process
I hava some code like this: class LooperThread extends Thread { public Handler mHandler;
I hava a webview showing some contents which is getting from server. Now on
I hava a some problem in .htaccess.. my site url is for ex. www.example.com/
I hava a UITextView ,and after some characters' input, I want to use a
i hava a c++ method(for java,jni) like follow,when i repeat call this from java
I hava a problem with an error in ADT Plugin. I want to make
I hava a CSV file that I want to treat as source code. Essentially

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.