Unity UWP加载图像字节缺少颜色通道

时间:2019-10-23 19:27:37

标签: c# unity3d uwp texture2d windows-mixed-reality

我正在加载图像字节,并尝试将其应用于Texture2D

不用担心异步/等待/线程问题...

UWP代码:

StorageFile storageFile = StorageFile.GetFileFromPathAsync(filePath).AsTask().GetAwaiter().GetResult();

// get image size
IRandomAccessStreamWithContentType random = storageFile.OpenReadAsync().AsTask().GetAwaiter().GetResult();
BitmapDecoder decoder = BitmapDecoder.CreateAsync(random).AsTask().GetAwaiter().GetResult();
BitmapFrame bitmapFrame = decoder.GetFrameAsync(0).AsTask().GetAwaiter().GetResult();
PixelDataProvider pixelData = bitmapFrame.GetPixelDataAsync().AsTask().GetAwaiter().GetResult();

return new Dictionary<string, object>
{
    {"bytes", pixelData.DetachPixelData()},
    {"width", (int) decoder.PixelWidth},
    {"height", (int) decoder.PixelHeight}
};

统一代码:

Texture2D texture = new Texture2D(textureSizeStruct.width, textureSizeStruct.height, TextureFormat.RGBA32, false);

texture.LoadRawTextureData(textureBytes);
texture.Apply();

这是图像显示的方式...

原件: enter image description here

在应用中(对不起的大白方块): enter image description here

2 个答案:

答案 0 :(得分:1)

您的图像通道不丢失,它们只是以不同的顺序

检查Texture2D.LoadRawTextureData的文档:

  

传递的数据应具有所需的大小,以根据其宽度,高度,数据格式和mipmapCount填充整个纹理;否则会引发UnityException。

解决方案:

TextureFormat.BGRA32传递给您的Texture2D构造函数。

答案 1 :(得分:0)

在UWP端,需要从解码器获取具有正确参数的像素。请按照以下解决方案进行操作:

StorageFile storageFile = StorageFile.GetFileFromPathAsync(filePath).AsTask().GetAwaiter().GetResult();
IRandomAccessStreamWithContentType random = storageFile.OpenReadAsync().AsTask().GetAwaiter().GetResult();
BitmapDecoder decoder = BitmapDecoder.CreateAsync(random).AsTask().GetAwaiter().GetResult();

// here is the catch
PixelDataProvider pixelData = decoder.GetPixelDataAsync(
    BitmapPixelFormat.Rgba8, // <--- you must to get the pixels like this
    BitmapAlphaMode.Straight,
    new BitmapTransform(),
    ExifOrientationMode.RespectExifOrientation,
    ColorManagementMode.DoNotColorManage // <--- you must to set this too
).AsTask().GetAwaiter().GetResult();