UE4从本地加载图片(JPG/PNG/BMP)为Texture2D
.h
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Engine.h"
#include "SimplePictureToolsLibrary.generated.h"
UCLASS()
class SIMPLEPICTURETOOLS_API USimplePictureToolsLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable,Category = "Picture Tool")
static bool LoadImageToTexture2D(const FString& ImagePath,UTexture2D* &InTexture,float& Width,float& Height);
};
.cpp
#include "SimplePictureToolsLibrary.h"
#include "IImageWrapperModule.h"
#include "IImageWrapper.h"
bool USimplePictureToolsLibrary::LoadImageToTexture2D(const FString& ImagePath, UTexture2D* &InTexture, float& Width, float& Height)
{
TArray<uint8> ImageReasultData;
FFileHelper::LoadFileToArray(ImageReasultData, *ImagePath);//读取图片的二进制数据
FString Ex = FPaths::GetExtension(ImagePath,false);//获取文件后缀
EImageFormat ImageFormat = EImageFormat::Invalid;
if (Ex.Equals(TEXT("jpg"), ESearchCase::IgnoreCase) || Ex.Equals(TEXT("jpeg"), ESearchCase::IgnoreCase))
{
ImageFormat = EImageFormat::JPEG;
}
else if (Ex.Equals(TEXT("bmp"), ESearchCase::IgnoreCase) )
{
ImageFormat = EImageFormat::BMP;
}
else if (Ex.Equals(TEXT("png"), ESearchCase::IgnoreCase))
{
ImageFormat = EImageFormat::PNG;
}
IImageWrapperModule&ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>("ImageWrapper");
TSharedPtr<IImageWrapper> ImageWrapperptr= ImageWrapperModule.CreateImageWrapper(ImageFormat);//创建对应格式图片壳子
bool PtrIsValid = ImageWrapperptr.IsValid();
if (PtrIsValid && ImageWrapperptr->SetCompressed(ImageReasultData.GetData(),ImageReasultData.GetAllocatedSize()))
{
const TArray<uint8> *OutRawData;//跟数据无关的颜色数据
ImageWrapperptr->GetRaw(ERGBFormat::BGRA, 8, OutRawData); //按规则提取数据
Width = ImageWrapperptr->GetWidth();
Height = ImageWrapperptr->GetHeight();
InTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);
if (InTexture)
{
void * TextureData=InTexture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcmp(TextureData, OutRawData->GetData(),OutRawData->Num());//将数据写入*TextureData
InTexture->PlatformData->Mips[0].BulkData.Unlock();
InTexture->UpdateResource();
return true;
}
}
return false;
};
``
PrivateDependencyModuleNames.AddRange(
new string[]
{
"CoreUObject",
"Engine",
"Slate",
"SlateCore",
"ImageWrapper",
// ... add private dependencies that you statically link with here ...
}
);
如上在项目.build.cs文件种添加 "ImageWrapper"模块。


本文档介绍了如何在UE4中从本地加载JPG、PNG和BMP格式的图片,并将它们转换为Texture2D对象。通过修改项目.build.cs文件并引入'ImageWrapper'模块,实现图片资源的加载和使用。
为Texture2D&spm=1001.2101.3001.5002&articleId=115179672&d=1&t=3&u=a52c8ca3b90b4a06a69d1787cdbfd9fe)
707

被折叠的 条评论
为什么被折叠?



