目录
UEC++ 加载本地图片(LoadImageFromFile)和本地文件夹内所有图片(LoadAllImagesFromFiles)
LoadPicture.h
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "LoadPicture.generated.h"
UCLASS()
class LOADPICTURE_API ULoadPicture : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "LoadPicture")
static UTexture2D* LoadImageFromFile(const FString& ImagePath);
UFUNCTION(BlueprintCallable, Category = "LoadPicture")
static TArray<FString> GetFolderFiles(FString& Path);
UFUNCTION(BlueprintCallable, Category = "LoadPicture")
static TArray<UTexture2D*> LoadAllImagesFromFiles(FString& Paths);
static TSharedPtr<class IImageWrapper> GetImageWrapperByExtention(const FString Path);
};
LoadPicture.cpp
#include "LoadPicture.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
UTexture2D* ULoadPicture::LoadImageFromFile(const FString& ImagePath)
{
if (ImagePath.IsEmpty()) {
return nullptr;
}
TArray<uint8> CompressedData;
if (!FFileHelper::LoadFileToArray(CompressedData, *ImagePath)) {
return nullptr;
}
TSharedPtr<IImageWrapper> ImageWrapper = GetImageWrapperByExtention(ImagePath);
if (!ImageWrapper->SetCompressed(CompressedData.GetData(), CompressedData.Num())) {
return nullptr;
}
TArray<uint8> UncompressedRGBA;
if (!ImageWrapper->GetRaw(ERGBFormat::RGBA, 8, UncompressedRGBA))
return nullptr;
UTexture2D* Texture2D= UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_R8G8B8A8);
if (!Texture2D)
return nullptr;
void* TextureData = Texture2D->GetPlatformData()->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(TextureData, UncompressedRGBA.GetData(), UncompressedRGBA.Num());
Texture2D->GetPlatformData()->Mips[0].BulkData.Unlock();
Texture2D->UpdateResource();
return Texture2D;
}
TArray<FString> ULoadPicture::GetFolderFiles(FString& Path)
{
TArray<FString> Files;
FPaths::NormalizeDirectoryName(Path);
IFileManager& FileManager = IFileManager::Get();
const FString FinalPath = Path / TEXT("*");
FileManager.FindFiles(Files, *FinalPath, true, true);
return Files;
}
TArray<UTexture2D*> ULoadPicture::LoadAllImagesFromFiles(FString& Paths)
{
TArray<FString> ImgPaths = GetFolderFiles(Paths);
TArray<UTexture2D*> Texture2DArr;
for (auto ItemPath : ImgPaths)
{
UTexture2D* Texture2D = LoadImageFromFile(Paths + "/" + ItemPath);
Texture2DArr.Add(Texture2D);
}
return Texture2DArr;
}
TSharedPtr<IImageWrapper> ULoadPicture::GetImageWrapperByExtention(const FString Path)
{
IImageWrapperModule& Module = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
if (Path.EndsWith(".png"))
{
return Module.CreateImageWrapper(EImageFormat::PNG);
}
if (Path.EndsWith(".jpg"))
{
return Module.CreateImageWrapper(EImageFormat::JPEG);
}
return nullptr;
}