1 UE4中将TextureRenderTarget2D保存为图片

为了更易扩展,我们可以将这个函数封装在UE的自定义插件中,首先在UE4中新建插件,然后新建一个C++类,其父类为蓝图函数库类,并且挂靠在新建的插件库中。

假如新建的蓝图函数库为MyBlueprintFunctionBPLibrary,
则MyBlueprintFunctionBPLibrary.h的代码为:

#include "Runtime/Engine/Public/ImageUtils.h"
UCLASS()
class UMyBlueprintFunctionBPLibrary : public UBlueprintFunctionLibrary
{
    GENERATED_UCLASS_BODY()

    //保存UTextureRenderTarget2D到本地文件
    UFUNCTION(BlueprintCallable, meta = (DisplayName = "SaveRenderTargetToFile", Keywords = "SaveRenderTargetToFile"), Category = "SaveToFile")
        static bool SaveRenderTargetToFile(UTextureRenderTarget2D* rt, const FString& fileDestination);
};

则MyBlueprintFunctionBPLibrary.cpp的代码为:

bool UMyBlueprintFunctionBPLibrary::SaveRenderTargetToFile(UTextureRenderTarget2D* rt, const FString& fileDestination)
{
    FTextureRenderTargetResource* rtResource = rt->GameThread_GetRenderTargetResource();
    FReadSurfaceDataFlags readPixelFlags(RCM_UNorm);

    TArray<FColor> outBMP;
    outBMP.AddUninitialized(rt->GetSurfaceWidth() * rt->GetSurfaceHeight());
    rtResource->ReadPixels(outBMP, readPixelFlags);

    for (FColor& color : outBMP)
        color.A = 255;

    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;
}

参考链接