繁体   English   中英

通过游戏将屏幕截图保存到Android画廊

[英]Saving Screenshot to android gallary via game

它需要屏幕截图,但不会显示在图库中。 屏幕截图已保存到android / data / com.company.name / file.name,但我想使用文件名屏幕截图直接将其保存到图库中

到目前为止,这里的代码是:

public void Capture() 
{
    string filename = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
    Application.CaptureScreenshot(filename + ".jpg");
    Debug.Log("captured screenshot");
}

寻找此处提供的答案(第二个)。 它运作完美。

这是最终代码:

protected const string MEDIA_STORE_IMAGE_MEDIA = "android.provider.MediaStore$Images$Media";
protected static AndroidJavaObject m_Activity;

protected static string SaveImageToGallery(Texture2D a_Texture, string a_Title, string a_Description)
{
    using (AndroidJavaClass mediaClass = new AndroidJavaClass(MEDIA_STORE_IMAGE_MEDIA))
    {
        using (AndroidJavaObject contentResolver = Activity.Call<AndroidJavaObject>("getContentResolver"))
        {
            AndroidJavaObject image = Texture2DToAndroidBitmap(a_Texture);
            return mediaClass.CallStatic<string>("insertImage", contentResolver, image, a_Title, a_Description);
        }
    }
}

protected static AndroidJavaObject Texture2DToAndroidBitmap(Texture2D a_Texture)
{
    byte[] encodedTexture = a_Texture.EncodeToPNG();
    using (AndroidJavaClass bitmapFactory = new AndroidJavaClass("android.graphics.BitmapFactory"))
    {
        return bitmapFactory.CallStatic<AndroidJavaObject>("decodeByteArray", encodedTexture, 0, encodedTexture.Length);
    }
}

protected static AndroidJavaObject Activity
{
    get
    {
        if (m_Activity == null)
        {
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            m_Activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        }
        return m_Activity;
    }
}

您只需致电:

string path = SaveImageToGallery(picture, "Test Picture", "This is a description.");

编辑:因为您似乎对Unity真的很陌生,所以建议您先学习它。 无论如何,您可以通过以下方式调用上面提供的代码:

public void CaptureScreenshot()
{
    StartCoroutine(CaptureScreenshotCoroutine(Screen.width, Screen.height));
}

private IEnumerator CaptureScreenshotCoroutine(int width, int height)
{
    yield return new WaitForEndOfFrame();
    Texture2D tex = new Texture2D(width, height);
    tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
    tex.Apply();

    yield return tex;
    string path = SaveImageToGallery(tex, "Name", "Description");
    Debug.Log("Picture has been saved at:\n" + path);
}

只需将这两个方法添加到您的代码中,然后从另一个脚本,一个Unity按钮或其他任何东西调用CaptureScreenshot()

希望这可以帮助,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM