UE4将读取的PNG图片数据转换为UTexture2D并显示

思路

  1. 从硬盘中读取压缩过的图片文件到二进制数组,获取已压缩的数据;
  2. 将已压缩的数据借助ImageWrapper中的GetRaw函数转换为原始RGB数据;
  3. 填充原始RGB数据到UTexture2D中。

准备

处理图片类型需要使用UE提供的ImageWrapper模块,首先在project.Build.cs中加入ImageWrapper模块。

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "ImageWrapper" });

ImageWrapper是所有图片类型的抽象层,其设计思路如下:

  1. 图片文件数据是经过压缩的数据,称为CompressedData;
  2. 图片文件对应的原始RGBA数据是没有压缩的,且与图片格式无关,称为RawData;
  3. 不同格式的同样图片,其RawData不变,CompressedData随格式而变;
  4. 所有图片格式都可以抽象为一个CompressedData与RawData的组合。

代码 

UFUNCTION(BlueprintCallable, Category = "ImagePlayer")
		static bool LoadImageToTexture2D(const FString& ImagePath, UTexture2D*& InTexture, int32& Width, int32& Height);
bool AImagePlayer::LoadImageToTexture2D(const FString& ImagePath, UTexture2D*& InTexture, int32& Width, int32& Height)
{
    if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*ImagePath))  //判断是否存在该文件
    {
        return false;
    }

    IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked <IImageWrapperModule>(FName("ImageWrapper"));//启用"ImageWrapper"模型
    TSharedPtr<IImageWrapper> SourceImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);//实例化ImageWrapper类,图片的类型为PNG


    TArray<uint8> SourceImageData;  //存储压缩的二进制图片数据
    if (!FFileHelper::LoadFileToArray(SourceImageData, *ImagePath)) //读取文件资源
    {
        return false;
    }


    if (SourceImageWrapper.IsValid() && SourceImageWrapper->SetCompressed(SourceImageData.GetData(), SourceImageData.GetAllocatedSize()))
    {
        TArray <uint8> UncompressedBGRA;    //存储未压缩的颜色数据,UE4用的颜色格式为BGRA
        if (SourceImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))  //获取未压缩的图片颜色信息,位深度为8
        {
            Height = SourceImageWrapper->GetHeight();	
            Width = SourceImageWrapper->GetWidth();

            InTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);	//临时填充

            if (InTexture)
            {
                void* TextureData = InTexture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);	//用自带方法"PlatformData"让InTexture和指针TextureData绑定(Lock)并且可读可写,因为下一行的复制函数中的参数要求为void*


                FMemory::Memcpy(TextureData, UncompressedBGRA.GetData(), UncompressedBGRA.Num());	//复制未压缩的颜色数据

                InTexture->PlatformData->Mips[0].BulkData.Unlock(); //将指针和InTexture解绑(unlock)

                InTexture->UpdateResource();    //刷新
                return true;
            }
        }
    }
    return false;

}

蓝图

创建Widget Blueprint,命名为ImageHUD,添加Image窗口,并勾选Size To Content。

 

使用LoadImageToTexture2D函数。

关卡蓝图中创建ImageHUD,并添加到视口。

 效果

 

参考 

《大象无形:虚幻引擎程序设计浅析》

B站:UE4 Image处理工具第一讲:从磁盘读取图片数据转成UTexture2D

猜你喜欢

转载自blog.csdn.net/qq_51505215/article/details/129485342