UE5_加载本地图片(jpg, png) 转 UTexture

发布于:2024-06-09 ⋅ 阅读:(194) ⋅ 点赞:(0)

UE5_加载图片到UTexture

__Desc

__Time__: 2024-06-05 16:30
__Author__: Yblackd
__Desc__: UE5.2 加载本地图片 转 UTexture2D, 给材质 和 UMG 使用

使用方式

  1. 新建继承BlueprintFunctionLibrary c++ 类
  2. 复制下面源码,修改类名
  3. 实测加载 jpg,jpeg, png 都可以; 其他未测试

源码

// .h
UFUNCTION(BlueprintCallable, Category = "UtilityBPLibrary | Texture")
static bool LoadImageToTexture(const FString& ImgPath, UTexture2D*& Texture2D);

// .cpp

bool UUtilityBPLibrary::LoadImageToTexture(const FString& ImgPath, UTexture2D*& Texture2D)
{
	if (!FPaths::FileExists(ImgPath))
	{
		YDLogWarnFormat("%s Img Not Exist", *ImgPath);
		return false;
	}

	TArray<uint8> FileData;
	if (!FFileHelper::LoadFileToArray(FileData, *ImgPath))
	{
		YDLogWarnFormat("%s Img Loading Failed ", *ImgPath);
		return false;
	}

	// 使用图像包装器模块 创建 图像包装器
	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
	EImageFormat ImageFormat = ImageWrapperModule.GetImageFormatFromExtension(*ImgPath);
	TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat);
	if (!ImageWrapper.IsValid())
	{
		YDLogWarnFormat("%s Img Loading Failed ", *ImgPath);
		return false;
	}

	// 解码 JPEG文件 到 FImage对象
	if (!ImageWrapper->SetCompressed(FileData.GetData(), FileData.Num()))
	{
		YDLogWarnFormat("%s Img 解码失败 ", *ImgPath);
		return false;
	}


	TArray<uint8> RawData;
	if (!ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, RawData))
	{
		YDLogWarnFormat("%s Img 获取原始数据失败 ", *ImgPath);
		return false;
	}

	int ImgWidgth = ImageWrapper->GetWidth();
	int ImgHeight = ImageWrapper->GetHeight();

	// 创建纹理
	Texture2D = UTexture2D::CreateTransient(ImgWidgth, ImgHeight, PF_B8G8R8A8);

	// 填充纹理数据
	FTexture2DMipMap& Mip = Texture2D->GetPlatformData()->Mips[0];
	void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE);
	FMemory::Memcpy(Data, RawData.GetData(), RawData.Num());
	Mip.BulkData.Unlock();

	// 设置纹理参数
	Texture2D->UpdateResource();

	return true;
}

网站公告

今日签到

点亮在社区的每一天
去签到