#include "IImageWrapperModule.h"
#include "IImageWrapper.h"
#include "IImageWrapperPublic.h"
#include "ImageUtils.h"
#include "TextureResource.h"
UTexture2D* ImportJpgToTexture(const FString& filePath, FName name, UObject* outer)
{
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*filePath))
{
return nullptr;
}
TArray<uint8> fileData;
if (!FFileHelper::LoadFileToArray(fileData, *filePath))
{
return nullptr;
}
TSharedPtr<IImageWrapper> imageWrapper = ImageWrapperModule->CreateImageWrapper(EImageFormat::JPEG);
if (!imageWrapper.IsValid() || !imageWrapper->SetCompressed(fileData.GetData(), fileData.Num()))
{
return nullptr;
}
TArray<uint8> uncompressedData;
if (!imageWrapper->GetRaw(ERGBFormat::BGRA, 8, uncompressedData))
{
return nullptr;
}
UTexture2D* texture = UTexture2D::CreateTransient(imageWrapper->GetWidth(), imageWrapper->GetHeight(), PF_B8G8R8A8);
void* textureData = texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(textureData, uncompressedData.GetData(), uncompressedData.Num());
texture->PlatformData->Mips[0].BulkData.Unlock();
texture->UpdateResource();
// Set the texture name and outer
texture->Rename(*name.ToString(), outer);
texture->AddToRoot();
return texture;
}
You can call this function with the path to the JPG file, a name for the texture, and the outer object where you want to create the texture. This function will return a UTexture2D object that contains the imported JPG image.