Skip to content Skip to sidebar Skip to footer

Saving Screenshot To Android Gallary Via Game

It takes the screenshot but doesn't show in gallery . the screenshot is saved to android/data/com.company.name/file.name but I want to save it directly to the gallery with filename

Solution 1:

Look for the answer provided here (the second one). It works perfectly.

Here's the final code:

protectedconststring MEDIA_STORE_IMAGE_MEDIA = "android.provider.MediaStore$Images$Media";
protectedstatic AndroidJavaObject m_Activity;

protectedstaticstringSaveImageToGallery(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);
        }
    }
}

protectedstatic 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);
    }
}

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

And you simply call:

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

EDIT: Since you seem really new to Unity I'd suggest learning it first. Anyway here's how you can call the code provided above:

publicvoidCaptureScreenshot()
{
    StartCoroutine(CaptureScreenshotCoroutine(Screen.width, Screen.height));
}

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

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

Simply add those two methods to your code and call the CaptureScreenshot() either from another script, a Unity Button, or anything else...

Hope this helps,

Post a Comment for "Saving Screenshot To Android Gallary Via Game"