The code is as follows:
UTexture2D* UFileOperator::LoadTexture2D_FromFile(const FString& FullFilePath, EJoyImageFormats ImageFormat, bool& IsValid, int32& Width, int32& Height){
IsValid = false;
UTexture2D* LoadedT2D = NULL;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(GetJoyImageFormat(ImageFormat));
if (FullFilePath.IsEmpty()) return NULL;
//Load From File
TArray<uint8> RawFileData;
if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) {
Width = 21; //Width is 21 if loading fails
Height = RawFileData.Num();
return NULL;
}
if (ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num())) {
Width = 7;
}
else {
Width = RawFileData.Num();
}
//Create T2D!
if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
{
const TArray<uint8>* UncompressedBGRA = NULL;
if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
//Valid?
if (!LoadedT2D) {
Width = 56;
return NULL;
}
//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;
}
And the blueprint node is
However, it doesnot load files successfully every time. It loads successfully only a few times… I know the problem is loading problem but not others, because when it fails, the Width is 21 just as what I write in my codes…
I know other developers have already implemented this function, so help please. Thanks:)