我正在尝试使用此代码将相机的Feed保存到png,但似乎无法正常工作:
void RecordAndSaveFrameTexture()
{
if (mXr.ShouldUseRealityRGBATexture())
{
SaveTextureAsPNG(mXr.GetRealityRGBATexture(), mTakeDirInfo.FullName + "/texture_" + mFrameInfo.mFrameCount.ToString() + ".png");
}
else
{
SaveTextureAsPNG(mXr.GetRealityYTexture(), mTakeDirInfo.FullName + "/texture_y_" + mFrameInfo.mFrameCount.ToString() + ".png");
SaveTextureAsPNG(mXr.GetRealityUVTexture(), mTakeDirInfo.FullName + "/texture_uv_" + mFrameInfo.mFrameCount.ToString() + ".png");
}
}
public static void SaveTextureAsPNG(Texture2D aTexture, string aFullPath)
{
byte[] bytes = aTexture.EncodeToPNG();
System.IO.File.WriteAllBytes(aFullPath, bytes);
Debug.Log("Image with Instance ID:" + aTexture.GetInstanceID() + "with dims of " + aTexture.width.ToString() + " px X " + aTexture.height + " px " + " with size of" + bytes.Length / 1024 + "Kb was saved as: " + aFullPath);
}
在非ArCore安卓上测试我获得了具有480 x 640像素的正确大小的黑色图像(具有随机彩色像素)。使用ArCore,它是一个0kb的黑色图像。
答案 0 :(得分:1)
直接从这些纹理创建图像无法正常工作,因为在可以呈现有效图像之前,此数据会通过XRCameraYUVShader
和XRARCoreCamera
传递。
一种选择是创建XRVideoController
的自定义版本,该版本可以访问用于渲染相机Feed的素材。从那里,你的代码可以这样修改:
void RecordAndSaveFrameTexture() {
Texture2D src = xr.ShouldUseRealityRGBATexture()
? xr.GetRealityRGBATexture()
: xr.GetRealityYTexture();
RenderTexture renderTexture = new RenderTexture (src.width, src.height, 0, RenderTextureFormat.ARGB32);
Graphics.Blit (null, renderTexture, xrMat);
SaveTextureAsPNG(renderTexture, Application.persistentDataPath + "/texture.png");
}
public static void SaveTextureAsPNG(RenderTexture renderTexture, string aFullPath) {
Texture2D aTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
RenderTexture.active = renderTexture;
aTexture.ReadPixels(new Rect(0, 0, aTexture.width, aTexture.height), 0, 0);
RenderTexture.active = null;
byte[] bytes = aTexture.EncodeToPNG();
System.IO.File.WriteAllBytes(aFullPath, bytes);
}
xrMat
是用于渲染相机Feed的材料。
这将为相机图像提供任何Unity游戏对象。如果您希望游戏对象显示在已保存的图像中,您可以覆盖OnRenderImage
来实现:
void OnRenderImage(RenderTexture src, RenderTexture dest) {
if (shouldSaveImageFrame) {
SaveTextureAsPNG(src, Application.persistentDataPath + "/_rgbatexture.png");
shouldSaveImageFrame = false;
}
Graphics.Blit (src, dest);
}
shouldSaveImageFrame
是您在其他地方设置的标志,以防止图像在每一帧上保存。