UE4 保存RenderTarget 到桌面

最近武汉疫情严重,在家没事,做一个保存截图的功能。话不多说,直接上步骤和代码

1我这里是新建的一个character蓝图作为载体,也可以建立其他actor蓝图,添加SceneCapture Componenet2D 组件

UE4 保存RenderTarget 到桌面

2修改右侧属性CaptureSource-> Final color (LDR) in RGB,如下图

UE4 保存RenderTarget 到桌面

3 同时创建专用贴图并指定上去

UE4 保存RenderTarget 到桌面

4双击打开贴图设置参数(因为我不需要太大的分辨率,所以就设置720的,rendertarget format 不需要更改,下面贴出的代码里控制,调节gamma值增强亮度)

UE4 保存RenderTarget 到桌面

5 引擎默认有一个到处的节点(4.23),但是导出后的png图片颜色有偏差,所以决定自己重写

UE4 保存RenderTarget 到桌面

6  新建c++蓝图类

UE4 保存RenderTarget 到桌面UE4 保存RenderTarget 到桌面

7 添加代码

UE4 保存RenderTarget 到桌面

UE4 保存RenderTarget 到桌面

完整代码:

 .h部分

#pragma once

#include "ImageUtils.h"

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "MyBlueprintFunctionLibrary.generated.h"

/**
 * 
 */
UCLASS()
class ROBOTDESIGNER_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()
    
    //保存UTextureRenderTarget2D到本地文件
    UFUNCTION(BlueprintCallable, meta = (DisplayName = "SaveRenderTargetToFile", Keywords = "SaveRenderTargetToFile"), Category = "SaveToFile")
        static bool SaveRenderTargetToFile(UTextureRenderTarget2D* rt, const FString& fileDestination);
};

 

.cpp 部分

#include "MyBlueprintFunctionLibrary.h"

#include "Engine/TextureRenderTarget2D.h"
#include "Misc/FileHelper.h"
bool UMyBlueprintFunctionLibrary::SaveRenderTargetToFile(UTextureRenderTarget2D* rt, const FString& fileDestination)
{
    FTextureRenderTargetResource* rtResource = rt->GameThread_GetRenderTargetResource();
    FReadSurfaceDataFlags readPixelFlags(RCM_UNorm);

    TArray<FColor> outBMP;

    for (FColor& color : outBMP)
    {
        color.A = 255;
    }
    outBMP.AddUninitialized(rt->GetSurfaceWidth() * rt->GetSurfaceHeight());
    rtResource->ReadPixels(outBMP, readPixelFlags);

    FIntPoint destSize(rt->GetSurfaceWidth(), rt->GetSurfaceHeight());
    TArray<uint8> CompressedBitmap;
    FImageUtils::CompressImageArray(destSize.X, destSize.Y, outBMP, CompressedBitmap);
    bool imageSavedOk = FFileHelper::SaveArrayToFile(CompressedBitmap, *fileDestination);

    return imageSavedOk;
}

 

8 编译,完成

UE4 保存RenderTarget 到桌面