虚幻引擎(UE)C++,加载读取本地路径图片、Texture2D

//通过路径获取单张图片,转为Texture2D

UFUNCTION(BlueprintCallable, Category = "Image")

static UTexture2D* LoadTexture2D(const FString ImagePath);

//获取指定路径下的所以有图片的名称

UFUNCTION(BlueprintCallable, Category = "Image")

static TArray GetFolderFiles(FString ImagePath);

//将指定路径下的所有图片转为Texture2D

UFUNCTION(BlueprintCallable, Category = "Image")

static TArray GetAllImageFromFiles(FString ImagePath);

//判断图片类型

static TSharedPtrGetImageWrapperByExtention(const FString ImagePath);

UTexture2D* ULoadImageToTexture::LoadTexture2D(const FString ImagePath)

{

UTexture2D* Texture = nullptr;

if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*ImagePath))

{

return nullptr;

}

TArray RawFileData;

if (!FFileHelper::LoadFileToArray(RawFileData, *ImagePath))

{

return nullptr;

}

TSharedPtr ImageWrapper = GetImageWrapperByExtention(ImagePath);

if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))

{

TArray UncompressedRGBBA;

if (ImageWrapper->GetRaw(ERGBFormat::RGBA, 8, UncompressedRGBBA))

{

Texture = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_R8G8B8A8);

if (Texture != nullptr)

{

void* TextureData = Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);

FMemory::Memcpy(TextureData, UncompressedRGBBA.GetData(), UncompressedRGBBA.Num());

Texture->PlatformData->Mips[0].BulkData.Unlock();

Texture->UpdateResource();

}

}

}

return Texture;

}

===============================================================================

TArray ULoadImageToTexture::GetFolderFiles(FString ImagePath)

{

TArrayfiles;

FPaths::NormalizeDirectoryName(ImagePath);

IFileManager& FileManager = IFileManager::Get();

FString FinalPath = ImagePath / TEXT("*");

FileManager.FindFiles(files, *FinalPath, true, true);

return files;

}

===============================================================================

TArray ULoadImageToTexture::GetAllImageFromFiles(FString ImagePath)

{

TArray ImgPath = GetFolderFiles(ImagePath);

TArrayTexture2DArr;

for (auto path : ImgPath)

{

UTexture2D* Texture2D = LoadTexture2D(ImagePath + "/" + path);

Texture2DArr.Add(Texture2D);

}

return Texture2DArr;

}

===============================================================================

TSharedPtr ULoadImageToTexture::GetImageWrapperByExtention(const FString ImagePath)

{

IImageWrapperModule& module = FModuleManager::LoadModuleChecked(FName("ImageWrapper"));

if (ImagePath.EndsWith(".png"))

{

return module.CreateImageWrapper(EImageFormat::PNG);

}

if (ImagePath.EndsWith(".jpg") || ImagePath.EndsWith("jpeg"))

{

return module.CreateImageWrapper(EImageFormat::JPEG);

}

return nullptr;

}

猜你喜欢

转载自blog.csdn.net/weixin_55943251/article/details/126723188