目标是将一个虚拟摄影机拍摄的图像保存成图像文件。
在场景中创建一个“场景捕获2D(SceneCapture2D)”,或者在任意Actor蓝图中增加组件“场景捕获组件2D(SceneCaptureComponent2D)”,并在其属性里的“纹理坐标”中创建/绑定一个“渲染目标(TextureRenderTarget2D)”,“捕获源”设置为“RGB最终颜色(LDR)”。
编辑渲染目标,修改属性中的尺寸,如1920*1080;“渲染目标格式”设置为“RTF RGBA8”;“目标伽马”设置为2.2。
增加以下代码:
#include "Engine/TextureRenderTarget2D.h"
#include "Misc/FileHelper.h"
#include "ImageUtils.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;
}
参考文章: