其他分享
首页 > 其他分享> > 【UE4】读写 Texture 数据

【UE4】读写 Texture 数据

作者:互联网

创建texture

void AActor_Assignment2::TextureFromImage_Internal( const TArray<FColor>& SrcData, const bool UseAlpha)
{
	const int32 SrcWidth = CanvasSize.X;
	const int32 SrcHeight = CanvasSize.Y;
	// Create the texture
	T_Result = UTexture2D::CreateTransient(CanvasSize.X, CanvasSize.Y, PF_B8G8R8A8);

	// Lock the texture so it can be modified
	uint8* MipData = static_cast<uint8*>(T_Result->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE));

	// Create base mip.
	uint8* DestPtr = NULL;
	const FColor* SrcPtr = NULL;
	for (int32 y = 0; y < SrcHeight; y++)
	{
		DestPtr = &MipData[(SrcHeight - 1 - y) * SrcWidth * sizeof(FColor)];
		SrcPtr = const_cast<FColor*>(&SrcData[(SrcHeight - 1 - y) * SrcWidth]);
		for (int32 x = 0; x < SrcWidth; x++)
		{
			*DestPtr++ = SrcPtr->B;
			*DestPtr++ = SrcPtr->G;
			*DestPtr++ = SrcPtr->R;
			if (UseAlpha)
			{
				*DestPtr++ = SrcPtr->A;
			}
			else
			{
				*DestPtr++ = 0xFF;
			}
			SrcPtr++;
		}
	}

	// Unlock the texture
	T_Result->PlatformData->Mips[0].BulkData.Unlock();
	T_Result->UpdateResource();
	
}
void AActor_Assignment3::BeginPlay()
{
	Super::BeginPlay();
	
	VideoTextureColor = UTexture2D::CreateTransient(640, 480, PF_B8G8R8A8);
	VideoTextureColor->UpdateResource();
	FUpdateTextureRegion2D* RegionColor = new FUpdateTextureRegion2D(0, 0, 0, 0, 640, 480);
	//FUpdateTextureRegionData* ColorRegionData = new FUpdateTextureRegionsData;
	
	// Populate the texture with blue color
	TArray<FColor> PixelDepthData;
	PixelDepthData.Init(FColor(255, 255, 0, 255), 640 * 480);


	VideoTextureColor->UpdateTextureRegions(
		(int32)0,
		(uint32)1,
		RegionColor,
		(uint32)(4 * 640),
		(uint32)4,
		(uint8*)PixelDepthData.GetData()
	);
	 VideoTextureColor->LODGroup = TEXTUREGROUP_Pixels2D;
	
}

访问Texture数据

	VideoTextureColor->CompressionSettings = TextureCompressionSettings::TC_VectorDisplacementmap;
	VideoTextureColor->MipGenSettings = TextureMipGenSettings::TMGS_NoMipmaps;
	VideoTextureColor->SRGB = false;  //确保这些设置,否则颜色容易丢失
	//VideoTextureColor->LODGroup = TEXTUREGROUP_Pixels2D;
	VideoTextureColor->UpdateResource();
	
	FTexture2DMipMap& Mip = VideoTextureColor->PlatformData->Mips[0];
	uint8* Data = (uint8*)Mip.BulkData.Lock(LOCK_READ_ONLY);
	// read here in low level:
	//let's say I want pixel x = 300, y = 23
	//basic formula, data[channels * (width * y + x)];
	FColor pixelColor = FColor(0, 0, 0, 255);
	int x = 200, y = 2;
	pixelColor.B = Data[4 * (640 * y + x) + 0];
	pixelColor.G = Data[4 * (640 * y + x) + 1];
	pixelColor.R = Data[4 * (640 * y + x) + 2];
	pixelColor.A = 255;

	Mip.BulkData.Unlock();
	VideoTextureColor->UpdateResource();
	UKismetSystemLibrary::PrintString(GetWorld(), TEXT("font color"), true, true, pixelColor);

访问材质上的点所对应贴图uv上的颜色

image

标签:const,VideoTextureColor,++,读写,DestPtr,Texture,640,SrcPtr,UE4
来源: https://www.cnblogs.com/shiroe/p/15438401.html