在Unity中如何在安卓设备上保存图像

3
我是新手学习Unity,想要保存一张图片并在之后使用。我尝试用Application.CaptureScreenshot和Texture2D.ReadPixel的方法,并尝试将它们保存到persistentDataPath(/data/user/0/my.package.name/files/)、/sdcard/Download/和/storage/emulated/0/Download中,但是没有任何方法有效。在我的项目的每个清单中都有WRITE_EXTERNAL_STORAGE权限。如果我保存到持久数据,我找不到它,我只能找到UnityAds的缓存,如果我保存到下载文件夹,我会收到访问权限被拒绝的错误提示。
可以帮助我吗?
以下是我的代码:
IEnumerator ScreenShot(){
         yield return new WaitForEndOfFrame ();
         Application.CaptureScreenshot ("ball.png");
         Application.CaptureScreenshot ("/sdcard/Download/ball.png");
         int width = Screen.width;
         int height = Screen.height;
         Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);
         tex.ReadPixels (new Rect (0, 0, width, height), 0, 0);
         tex.Apply ();
         byte[] bytes = tex.EncodeToJPG ();
         File.WriteAllBytes ("sdcard/Download/ball.png", bytes);
         File.WriteAllBytes (Application.persistentDataPath + "/ball.png", bytes);
 }

在检查文件夹是否存在之前:

if(!System.IO.Directory.Exists("/sdcard/Download/"))
{ 
    System.IO.Directory.CreateDirectory ("/sdcard/Download/"); 
}

if(!System.IO.Directory.Exists(Application.persistentDataPath))
{
    System.IO.Directory.CreateDirectory (Application.persistentDataPath);
}

我使用以下代码开始IEnumerator:

StartCoroutine(ScreenShot());

我做错了什么?

没成功,我已经尝试过使用 'Application.persistentDataPath + "/ball.png"' 和 '"file://" + Application.persistentDataPath + "/ball.png"' 进行分享。 - rickyxd
byte[] bytes = File.ReadAllBytes(Application.persistentDataPath + "/ball.png"); 将文件夹中的 ball.png 文件读取为字节数组。 - Everts
我用以下代码获取它:AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse", image); - rickyxd
这是正确的吗?很抱歉,我的经验不够丰富。 - rickyxd
Android 6给我们带来了很多痛苦、泪水和困扰,特别是在Unity方面。Android 6改变了很多东西... - Everts
显示剩余8条评论
1个回答

1
这是对我有效的方法:
    string destination = DateTime.Now.ToString ("yyyy-MM-dd-HHmmss") + ".png";
    string fullDestination = Path.Combine (Application.persistentDataPath, destination);

    Application.CaptureScreenshot (destination);

    SharingWriter.WriteTextInstant ("Preparing...");

    FileInfo fileInfo = new FileInfo(fullDestination);
    while(fileInfo == null || fileInfo.Exists == false)
    {
        yield return null;
        fileInfo = new FileInfo(fullDestination);
    }

Application.CaptureScreenshot可以处理一切,无需担心读取像素和写入文件,这是多余的。只需在Coroutine中之后使用while循环等待奇迹发生即可!我使用它创建了移动设备截图共享功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接