Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Image to Texture on UE4
static EImageFormat::Type GetJoyImageFormat(EJoyImageFormats JoyFormat)
{
switch (JoyFormat) {
case EJoyImageFormats::JPG: return EImageFormat::JPEG;
case EJoyImageFormats::PNG: return EImageFormat::PNG;
case EJoyImageFormats::BMP: return EImageFormat::BMP;
case EJoyImageFormats::ICO: return EImageFormat::ICO;
case EJoyImageFormats::EXR: return EImageFormat::EXR;
case EJoyImageFormats::ICNS: return EImageFormat::ICNS;
}
return EImageFormat::JPEG;
}
static FString GetJoyImageExtension(EJoyImageFormats JoyFormat)
{
switch (JoyFormat) {
case EJoyImageFormats::JPG: return ".jpg";
case EJoyImageFormats::PNG: return ".png";
case EJoyImageFormats::BMP: return ".bmp";
case EJoyImageFormats::ICO: return ".ico";
case EJoyImageFormats::EXR: return ".exr";
case EJoyImageFormats::ICNS: return ".icns";
}
return ".png";
}
UTexture2D* UHitMeSingleton::LoadTexture2DFromFile(const FString& FileName, EJoyImageFormats ImageFormat, bool& IsValid, int32& Width, int32& Height)
{
IsValid = false;
UTexture2D* LoadedT2D = NULL;
bool isOK = UWebImageDownloader::CreateWebImageFolder();
if (!isOK) return LoadedT2D;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(GetJoyImageFormat(ImageFormat));
//Load From File
FString FullFilePath = UWebImageDownloader::WebImageFolder() + "/" + FileName + GetJoyImageExtension(ImageFormat);
TArray<uint8> RawFileData;
if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) return NULL;
//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) 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;
}
UENUM(BlueprintType)
enum class EJoyImageFormats : uint8
{
JPG UMETA(DisplayName = "JPG"),
PNG UMETA(DisplayName = "PNG"),
BMP UMETA(DisplayName = "BMP"),
ICO UMETA(DisplayName = "ICO"),
EXR UMETA(DisplayName = "EXR"),
ICNS UMETA(DisplayName = "ICNS")
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment