UE 使用蓝图/C++加载硬盘外部图片

UE开发中经常会遇到加载外部图片的需求,通常是编写C++函数实现,不过使用蓝图加载可以更方便,就来看下。
在这里插入图片描述


蓝图实现

1.新建蓝图,使用节点Import File as Texture2D。传入路径使用ProjectDir,为程序的根目录,对于非打包状态即为Content外的那一级目录,对于打包后的程序为根目录。
在这里插入图片描述
2.在蓝图中创建测试材质球,并暴露Texture参数以测试。
在这里插入图片描述

3.在蓝图中创建动态材质示例,赋值Param材质参数。
在这里插入图片描述

C++实现

来讲下C++实现。

UTexture2D* LoadTextureFromFile(const FString& FilePath)
{
    // 检查文件是否存在
    if (!FPaths::FileExists(FilePath))
    {
        UE_LOG(LogTemp, Error, TEXT("File does not exist: %s"), *FilePath);
        return nullptr;
    }

    // 读取文件到数组
    TArray<uint8> RawFileData;
    if (!FFileHelper::LoadFileToArray(RawFileData, *FilePath))
    {
        UE_LOG(LogTemp, Error, TEXT("Failed to load file: %s"), *FilePath);
        return nullptr;
    }

    // 使用 ImageWrapperModule 解析图片
    IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));

    EImageFormat::Type ImageFormat = ImageWrapperModule.DetectImageFormat(RawFileData.GetData(), RawFileData.Num());
    if (ImageFormat == EImageFormat::Invalid)
    {
        UE_LOG(LogTemp, Error, TEXT("Unsupported image format for file: %s"), *FilePath);
        return nullptr;
    }

    TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat);
    if (!ImageWrapper.IsValid() || !ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
    {
        UE_LOG(LogTemp, Error, TEXT("Failed to parse image: %s"), *FilePath);
        return nullptr;
    }

    const TArray<uint8>* RawData = nullptr;
    if (!ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, RawData))
    {
        UE_LOG(LogTemp, Error, TEXT("Failed to get raw image data: %s"), *FilePath);
        return nullptr;
    }

    int32 Width = ImageWrapper->GetWidth();
    int32 Height = ImageWrapper->GetHeight();

    // 创建 UTexture2D 对象
    UTexture2D* NewTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);
    if (!NewTexture)
    {
        UE_LOG(LogTemp, Error, TEXT("Failed to create transient texture"));
        return nullptr;
    }

    NewTexture->MipGenSettings = TMGS_NoMipmaps;
    NewTexture->CompressionSettings = TC_VectorDisplacementmap;
    NewTexture->SRGB = true;

    // 填充纹理数据
    FTexture2DMipMap& Mip = NewTexture->PlatformData->Mips[0];
    void* TextureData = Mip.BulkData.Lock(LOCK_READ_WRITE);
    FMemory::Memcpy(TextureData, RawData->GetData(), RawData->Num());
    Mip.BulkData.Unlock();

    // 更新纹理
    NewTexture->UpdateResource();

    return NewTexture;
}

用法:

FString ImagePath = FPaths::ProjectContentDir() / TEXT("Textures/Example.png");
UTexture2D* Texture = LoadTextureFromFile(ImagePath);

if (Texture)
{
    UE_LOG(LogTemp, Log, TEXT("Texture loaded successfully!"));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值