You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UnrealEngine C++:如何将内存PNG图像转换为TArray缓冲区

Unreal Engine C++:内存PNG转TArray缓冲区实现

场景1:已有内存中的PNG字节数据

如果你的PNG已经以连续字节块的形式存在内存中(比如从文件读取、网络下载得到的uint8*指针和数据长度),直接将数据复制到TArray<uint8>即可:

// 假设你已获取到PNG数据指针和长度
uint8* PngRawData = ...;
int32 PngDataSize = ...;

TArray<uint8> ima_buf;
// 预分配内存
ima_buf.SetNumUninitialized(PngDataSize);
// 复制数据到TArray
FMemory::Memcpy(ima_buf.GetData(), PngRawData, PngDataSize);

场景2:运行时生成图像并编码为PNG存入TArray

如果是自己生成像素数据后需要编码为PNG格式,需借助Unreal的ImageWrapper模块:

  1. 添加模块依赖
    在项目的Build.cs文件中添加ImageWrapper依赖:
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "ImageWrapper" });
  1. 编码像素数据为PNG并写入TArray
#include "IImageWrapperModule.h"
#include "IImageWrapper.h"

// 示例:生成512x512的纯色像素数据
const int32 ImgWidth = 512;
const int32 ImgHeight = 512;
TArray<FColor> PixelData;
PixelData.SetNum(ImgWidth * ImgHeight);
FMemory::Memset(PixelData.GetData(), 255, PixelData.Num() * sizeof(FColor)); // 填充白色

// 加载ImageWrapper模块
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(TEXT("ImageWrapper"));
TSharedPtr<IImageWrapper> PngWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);

// 将像素数据编码为PNG格式
if (PngWrapper->SetRaw(PixelData.GetData(), PixelData.Num() * sizeof(FColor), ImgWidth, ImgHeight, ERGBFormat::BGRA, 8))
{
    // 将编码后的PNG字节写入ima_buf
    PngWrapper->GetRaw(ima_buf);
}

最终导入为Texture2D

完成缓冲区填充后,即可调用你原有的代码生成纹理:

UTexture2D* texture = FImageUtils::ImportBufferAsTexture2D(ima_buf);
// 可选:设置纹理属性并更新资源
if (texture)
{
    texture->SRGB = true;
    texture->CompressionSettings = TC_VectorDisplacementmap; // 根据需求修改压缩设置
    texture->UpdateResource();
}

内容的提问来源于stack exchange,提问作者Roberto Casalegno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:07:09