UE4:图像转纹理

使用UE4的ImageWrapperModule可以获取图像文件的信息,这些信息有助于创建UTexture2D纹理对象。

1、内存图像转纹理对象

使用如下代码将内存中的图像数据(可能来自磁盘或网络,也可能是程序化生成)转化为UTexture2D对象:

UTexture2D* USomeClassOfYours::LoadTexture2D_FromBuffer(const TArray<uint8>& RawFileData, EImageFormat ImageFormat, bool& IsValid, int32& Width, int32& Height)
{
    IsValid = false;
    UTexture2D* LoadedT2D = nullptr;
    
    IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
    TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat);
 
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      
    //Create T2D!
    if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
    { 
        TArray<uint8> UncompressedBGRA;
        if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
        {
            LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
            
            //Valid?
            if(!LoadedT2D) return nullptr;
            //~~~~~~~~~~~~~~
            
            //Out!
            Width = ImageWrapper->GetWidth();
            Height = ImageWrapper->GetHeight();
             
            //Copy!
            void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
            FMemory::Memcpy(TextureData, UncompressedBGRA.GetData(), UncompressedBGRA.Num());
            LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();

            //Update!
            LoadedT2D->UpdateResource();
        }
    }
     
    // Success!
    IsValid = true;
    return LoadedT2D;
}

2、磁盘文件转纹理对象

使用如下代码将指定路径的图像文件转化为UE4的纹理对象:

UTexture2D* USomeClassOfYours::LoadTexture2D_FromFile(const FString& FullFilePath, EImageFormat ImageFormat, bool& IsValid, int32& Width, int32& Height)
{ 
    //Load From File
    TArray<uint8> RawFileData;
    if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) return nullptr;
    
    return LoadTexture2D_FromBuffer(RawFileData, ImageFormat, IsValid, Width, Height);
}

原文链接:UnrealEngine - how to get buffer from in-memory image

BimAnt翻译整理,转载请标明出处