应用程序未在手机上保存 png 文件 - 团结



我正在制作一个关于 Unity 的相机应用程序,用于学习目的。我按照两个教程运行了我的凸轮现在这是我在堆栈溢出上找到的代码,问题是它没有将输出保存在手机上。

public void Pic()
{
StartCoroutine(TakePhoto());
}
IEnumerator TakePhoto()  // Start this Coroutine on some button click
{
// NOTE - you almost certainly have to do this here:
yield return new WaitForEndOfFrame();
Texture2D photo = new Texture2D(backCam.width, backCam.height);
photo.SetPixels(backCam.GetPixels());
photo.Apply();
//Encode to a PNG
byte[] bytes = photo.EncodeToPNG();
//Write out the PNG. Of course you have to substitute your_path for something sensible
File.WriteAllBytes(Application.dataPath + "photo.png", bytes);
}

我已将Pic()附加到按钮上。

我只是在学习这些,所以可能会犯一些愚蠢的错误。

它必须是/photo.png,否则你只是将文件名附加到文件夹名

您还应该考虑切换到 persistentDataPath 并验证它是否为 file io(检查它是否存在是一种很好的做法(

对于路径,您应该始终使用Path.Combine而不是直接string串联

Path.Combine(Application.dataPath, "photo.png")

也有可能文件夹或文件根本不存在,因此您可以在编写之前检查并在这种情况下创建它们

var filePath = Path.Combine(Application.dataPath, "photo.png");
if (!Directory.Exists(Application.dataPath))
{
Directory.CreateDirectory(Application.dataPath);
}
if (!File.Exists(filePath))
{
File.Create(filePath);
}
//Write out the PNG. Of course you have to substitute your_path for something sensible
File.WriteAllBytes(filePath, bytes);

您需要在文件名前添加斜杠。

File.WriteAllBytes($"{Application.dataPath}/photo.png", bytes);

最新更新