How can I save a RenderTarget or a Texture to a file?

I’ve seen this question asked in a few different ways, but no one seems to be able to give a definitive answer.

To sum up, I’m using a SceneCaptureComponent2D to render to a RenderTarget. I want to save that RenderTarget to disk, at runtime. Everything with this is working fine, I just don’t know how to do the last step of saving it to a file.

To be more explicit on what I’m trying to create, we have a literal camera in our game that the player can use to take pictures. We want to save these pictures to disk so that the player can share them.

A solution in Blueprint is preferred, but C++ is not a problem.

+1 I would also like to know this.

I wasn’t able to find anything built in, so I ended up writing something myself. I’m relying on FHighResScreenshotConfig, as it already does most of the work. You could probably dig into it if you need more control.

The loop to set the alpha was a bit of a hack fix. For some reason, the alpha isn’t set correctly on the render target, so you need to manually set it before saving.

void SaveRenderTargetToDisk( UTextureRenderTarget2D* InRenderTarget, FString Filename )
{
    FTextureRenderTargetResource* RTResource = InRenderTarget->GameThread_GetRenderTargetResource();

    FReadSurfaceDataFlags ReadPixelFlags( RCM_UNorm );
    ReadPixelFlags.SetLinearToGamma( true );

    TArray<FColor> OutBMP;
    RTResource->ReadPixels( OutBMP, ReadPixelFlags );

    for( FColor& color : OutBMP )
    {
        color.A = 255;
    }


    FIntRect SourceRect;

    FIntPoint DestSize( InRenderTarget->GetSurfaceWidth(), InRenderTarget->GetSurfaceHeight() );


    FString ResultPath;
    FHighResScreenshotConfig& HighResScreenshotConfig = GetHighResScreenshotConfig();
    HighResScreenshotConfig.SaveImage( Filename, OutBMP, DestSize, &ResultPath );
}

Very nice! This was the only thing I could find that got this working! It’s really slow though, saving PNGs takes a lot of time. Do you have any idea how to improve that?

it seems not working if I use UTextureRenderTargetCube

I have not FHighResScreenshotConfig class, Can you give to me? thank you very much.

I have find the FHighResScreenshotConfig class, and very thanks your guide。 How about if use UTextureRenderTargetCube? expecting answer.

have you find the answer?