UE5 保存纹理

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "IImageWrapperModule.h"
#include "ImageWrapperHelper.h"
#include "Misc/FileHelper.h"
#include "AsyncImageExport.h"
#include "Engine/Texture2D.h"
#include "Engine/TextureRenderTarget2D.h"

void SaveTexture(UTexture2D* Texture, const FString& OutputPath)
{
if (!Texture) return;

IImageWrapperModule& ImageWrapperModule = FModuleManager::Get().LoadModuleChecked<IImageWrapperModule>(
TEXT("ImageWrapper"));
const TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);

if (ImageWrapper)
{
const int32 width = Texture->GetSizeX();
const int32 height = Texture->GetSizeY();

const FColor* data = (FColor*)Texture->GetPlatformData()->Mips[0].BulkData.Lock(LOCK_READ_WRITE);

ImageWrapper->SetRaw(data,
Texture->GetPlatformData()->Mips[0].BulkData.GetBulkDataSize(),
width, height,
ERGBFormat::BGRA, 8);

const TArray64<uint8>& CompressedByteArray = ImageWrapper->GetCompressed();

FFileHelper::SaveArrayToFile(CompressedByteArray, *OutputPath);

UE_LOG(LogTemp, Log, TEXT("Export Texture to %s"), *OutputPath);
Texture->GetPlatformData()->Mips[0].BulkData.Unlock();
}
}

void SaveRenderTarget(UTextureRenderTarget2D* Texture, const FString& OutputPath)
{
if (!Texture) return;

const int32 width = Texture->SizeX;
const int32 height = Texture->SizeY;

TArray<FColor> Data;
Data.AddUninitialized(width * height);

if (Texture->GameThread_GetRenderTargetResource()->ReadPixelsPtr(Data.GetData(), FReadSurfaceDataFlags()))
{
IImageWrapperModule& ImageWrapperModule = FModuleManager::Get().LoadModuleChecked<IImageWrapperModule>(
TEXT("ImageWrapper"));
const TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);
if (!ImageWrapper.Get()) return;

ImageWrapper->SetRaw(Data.GetData(), Data.GetAllocatedSize(),
width, height,
ERGBFormat::BGRA, 8);
const TArray64<uint8>& CompressedByteArray = ImageWrapper->GetCompressed(100);
FFileHelper::SaveArrayToFile(CompressedByteArray, *OutputPath);
UE_LOG(LogTemp, Log, TEXT("Export RenderTarget to %s"), *OutputPath);
}
}

UE5 保存纹理
https://automask.github.io/wild/2022/11/21/lab/S_Unreal_SaveTexture/
作者
Kyle Zhou
发布于
2022年11月21日
许可协议